【问题标题】:Vue.js Component doesn't show data from method of componentVue.js 组件不显示来自组件方法的数据
【发布时间】:2017-03-24 15:23:53
【问题描述】:

我是 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'

});

这将返回一个白屏。如果我删除数据,并在任务模板中使用一个字符串,它会显示该字符串,因此组件“任务”在组件“列表”中工作。

Vue.component('list', {

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


});


Vue.component('task', {

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

});


new Vue({

    el: '#root'

});

因此,使用方法/数据将数据显示到视图似乎有问题。我已经尝试了很多东西,但我就是做不好。

任何帮助都会很棒,在此先感谢

【问题讨论】:

    标签: javascript vue.js vuejs2 vue-component


    【解决方案1】:

    据记录 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>

    【讨论】:

    • 如果你安装了 Vue Devtools,当页面尝试渲染时,你会在你的开发控制台中看到这个错误。
    • 我知道这一点.. 到处寻找代码中的错误,但没有注意到我忘记包含它。一定是累了:)谢谢
    猜你喜欢
    • 1970-01-01
    • 2020-05-14
    • 2017-06-01
    • 2017-01-06
    • 2017-05-28
    • 2019-03-27
    • 1970-01-01
    • 2021-06-28
    • 1970-01-01
    相关资源
    最近更新 更多