首页 文章

Vuejs - 动态地将组件附加到div

提问于
浏览
0

我正在构建一个简单的博客应用程序在这个应用程序中,我有博客 Headers 列表,并点击博客 Headers (链接或在div上)我想在博客 Headers 下方动态地显示博客内容(从服务器获取数据的简单组件) . 但我无法得到如何将组件附加到点击的Div . 这是jsfiddle https://jsfiddle.net/x8g3d5wn/6/

在此示例中,单击“Blog Title1”Div应将“问候”组件附加到此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.'
    }
  }
});

1 回答

  • 1

    试试这个 .

    好像你的结构有点偏 . 虽然它可以这样使用,但vue不是jquery的替代品 . 更自然的方式是将博客文章存储在数组中,并通过组件显示它们 .

    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小提琴:https://jsfiddle.net/x8g3d5wn/9/

相关问题