Vuejs - 将组件动态附加到 div

Vuejs - dynamically attaching component to a div

我正在构建一个简单的博客应用程序。在此应用程序中,我有博客标题列表并单击博客标题(Link 或 div)我想动态显示博客内容(从服务器获取数据的简单组件)在博客标题下方。但是我不知道如何将组件附加到单击的 Div 。这是jsfiddle https://jsfiddle.net/x8g3d5wn/6/

在此示例中,单击 "Blog Title1" Div 应将 "greetings" 组件附加到此 div 并从其他 Div 中删除(在这个案例来自 "Blog Title 3") 。请告知或是否有任何其他简单的解决此类问题的方法。?谢谢。

<div id="app">    
      <div class="redColor hClass">
        Blog Title1
      </div>    
      <div class="grayColor hClass">
        Blog Title2
      </div>    
      <div class="tealColor hClass">
        Blog Title3
        <greeting></greeting>    
      </div>      
    </div>


Vue.component('greeting', {
  template: '<h1>Blog Text</h1>{{ message }}',
  data: {
    message: 'hello'
  }
});

var app = new Vue({
  el: '#app',
  data: function() {
    return {
      msg: 'Hello World! This is a Event listener test1.'
    }
  }
});

试试这个。

看来你的结构有点不对劲。虽然它可以这样使用,但 vue 不能替代 jquery。更多的"natural"方式是将博文存储在数组中,并通过组件显示它们。

Vue.component('blog', {
  template: '<div :class="post.className"><h1>{{post.title}}</h1><p v-if="show">{{ post.description }}</p></div>',
  props: ['post', 'show']
});

var app = new Vue({
  el: '#app',
  data: function() {
return {
 open: -1,
  blogposts: [
    {title:"Blog Title 1", description: "Ipsum to the Lorem", className:'redColor'},
    {title:"Blog Title 2", description: "Ipsum to the Lorem", className:"grayColor"},
    {title:"Blog Title 3", description: "Ipsum to the Lorem"}
  ]
}
  },
  methods: {
   openPost(i){
 if (this.open === i) {
   this.open = null
  }
  else {
   this.open = i
  }
}
  }
});
.redColor {
  background-color:red;
}

.grayColor {
  background-color:#999;
}

.tealColor {
  background-color:teal;
}

.hClass{
  min-height:50px;
  width:150px;
  margin-top:20px;
} 
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.0.3/vue.js"></script>
<div id="app">
<blog v-for="(b, i) in blogposts" :key="i" :post="b" :show="open === i" @click.native="openPost(i)"/>
</div>

js fiddle: https://jsfiddle.net/x8g3d5wn/9/