首先我们需要准备一个待办事项数组。添加
data
属性到
App.vue
组件对象中,它包含一个
ToDoItems
字段,其值是待办事项数组。在最终完成添加新的待办事项功能之前,我们可以先 mock 一些待办项目,每个待办项目可以用一个对象表示,这个对象含有
label
和
done
属性。
像下面这样添加一些待办项目让我们可以利用
v-for
来对它们进行渲染。
export default {
name: "app",
components: {
ToDoItem,
data() {
return {
ToDoItems: [
{ label: "Learn Vue", done: false },
{ label: "Create a Vue project with the CLI", done: true },
{ label: "Have fun", done: true },
{ label: "Create a to-do list", done: false },
现在我们有了一个列表,可以用 v-for
去展示它们了。指令的作用方式和元素的属性类似,就 v-for
而言,它类似 JavaScript 中的 for...in
循环——v-for="item in items"
——items
是你要迭代的列表,item
是数组中当前元素的引用。
v-for
获取每个迭代的元素,并渲染它和它的子元素。在我们的例子中,我们用 <li>
的形式展示每一个待办事项,接下来我们会通过每个待办事项传递数据到其对应的 ToDoItem
组件。