Vue.js组件不显示组件方法的数据

时间:2017-03-24 15:23:54

标签: javascript vue.js vuejs2 vue-component

我是Vue.JS(2)的新手,现在我正在尝试学习组件。我尝试将另一个组件中的组件与数据方法中的数据一起使用(我知道您不能在组件中使用属性Data)。我的代码现在:

HTML

<div id="root">

    <h1>Tasks</h1>

    <list></list>

</div>

JS

Vue.component('list', {

    template: '<task v-for="task in tasks">{{ task.task }}</task>',

    data: function()  {

        return {

            tasks: [

                {task: 'Go to the store', completed: false},
                {task: 'Go to the shop', completed: true},
                {task: 'Go to the mall', completed: true}
            ]

        };
    }

});


Vue.component('task', {

    template: '<li><slot></slot></li>'

});


new Vue({

    el: '#root'

});

这将返回白色屏幕。如果我删除数据,只是在任务模板中使用一个字符串,它就会显示字符串,所以组件&#34; task&#34;正在使用组件&#34; list&#34;。

Vue.component('list', {

    template: '<task>Test</task>',


});


Vue.component('task', {

    template: '<li><slot></slot></li>'

});


new Vue({

    el: '#root'

});

因此,使用方法/数据向视图显示数据似乎有问题。我尝试了很多东西,但我无法做到。

任何帮助都会很棒,提前谢谢

1 个答案:

答案 0 :(得分:2)

记录在案here

  

组件必须只包含一个根节点。

在顶级元素上放置v-for会使其重复。如果将该元素包装在div中,则可以正常工作。

如果你想编写自己的render函数,看起来你可以绕过这个限制。

Vue.component('my-list', {
  template: '<div><task v-for="task in tasks">{{ task.task }}</task></div>',
  data() {
    return {
      tasks: [{
          task: 'Go to the store',
          completed: false
        },
        {
          task: 'Go to the shop',
          completed: true
        },
        {
          task: 'Go to the mall',
          completed: true
        }
      ]
    };
  }
});

Vue.component('task', {
  template: '<li><slot></slot></li>'
});

new Vue({
  el: '#root'
});
<script src="//cdnjs.cloudflare.com/ajax/libs/vue/2.2.5/vue.min.js"></script>
<div id="root">
  <h1>Tasks</h1>
  <my-list></my-list>
</div>