我正在学习 Vue.js,但我不明白为什么 <li>{{task.body}}</li>
没有显示在屏幕上。
我创建了<tasks v-for="task in tasks"></tasks>
组件,它需要访问父组件的数据。
参见:https://jsfiddle.net/pd03t1vm/
HTML:
<div id="app">
<tasks v-for="task in tasks"></tasks>
</div>
<template id="tasks-template">
<ul>
<li>{{task.body}}</li>
</ul>
</template>
JS:
Vue.component('tasks', {
template: '#tasks-template',
});
new Vue({
el: '#app',
data: {
tasks: [
{body: 'Task 1 Something', completed: false},
{body: 'Task 2 Something', completed: true},
{body: 'Task 3 Something', completed: false},
{body: 'Task 4 Something', completed: false}
]
}
});
最佳答案
问题是您正在实例化 <tasks>
组件中的数据来自根组件,但您没有将当前任务传递到 <tasks>
组件,因此它根本无法访问它。
The Vue.js guide explains how to pass the data into a component using props :
首先需要绑定(bind)当前的tasks
到 item
的 prop(这里我称之为 <task>
)组件
<div id="app">
<tasks v-for="task in tasks" :item="task"></tasks>
</div>
请注意,您使用 :
绑定(bind)实际对象。在属性名称前面。
现在您需要定义 item
属性(property)在<tasks>
组件:
Vue.component('tasks', {
props: ['item'],
template: '#tasks-template',
});
顺便说一下:您的代码创建了 <tasks>
的四个实例。组件,以防万一您想知道 - 这可能不是您期望代码执行的操作。
关于javascript - 组件 - 从父级获取数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39196077/