在 Vue 里,一个组件实质上是一个拥有预定义选项的一个 Vue 实例:(单独测试的时候记得new Vue()渲染)
Vue.component(
'todo-item', {
template:
'<li>This is a todo</li>'
})
|
现在你可以在另一个组件模板中写入它:
<ol>
<todo-item>
</todo-item>
</ol>
|
但是这样会为每个 todo 渲染同样的文本,这看起来并不是很酷。我们应该将数据从父作用域传到子组件。让我们来修改一下组件的定义,使得它能够接受一个 prop
字段(属性):
props 把数据传给子组件!!!
“prop” 是组件数据的一个字段,期望从父作用域传下来。子组件需要显式地用 props 选项 声明 props:
Vue.component(
'todo-item', {
props: [
'todo'],
template:
'<li>{{ todo.text }}</li>'
})
|
现在,我们可以使用 v-bind
指令将 todo 传到每一个重复的组件中:
<div id="app-7">
<ol>
<todo-item v-for="item in groceryList" v-bind:todo="item">
</todo-item>
</ol>
</div>
|
Vue.component(
'todo-item', {
props: [
'todo'],
template:
'<li>{{ todo.text }}</li>'
})
var app7 =
new Vue({
el:
'#app-7',
data: {
groceryList: [
{
text:
'Vegetables' },
{
text:
'Cheese' },
{
text:
'Whatever else humans are supposed to eat' }
]
}
})
|
- Vegetables
- Cheese
- Whatever else humans are supposed to eat