<script setup>
import { ref } from 'vue'
// 给每个 todo 对象一个唯一的 id
let id = 0
const newTodo = ref('')
const todos = ref([
{ id: id++, text: 'Learn HTML' },
{ id: id++, text: 'Learn JavaScript' },
{ id: id++, text: 'Learn Vue' }
])
function addTodo() {
// ...
const text = newTodo.value
todos.value.push({
id:id++,
text:text
})
// newTodo.value = ''
}
function removeTodo(todo) {
// ...
}
</script>
<template>
<form @submit.prevent="addTodo">
<input v-model="newTodo" required placeholder="new todo">
<button>Add Todo</button>
</form>
<ul>
<li v-for="todo in todos" :key="todo.id">
{{ todo.text }}
<button @click="removeTodo(todo)">X</button>
</li>
</ul>
</template>
v-for="todo in todos"
就是告诉 Vue 去遍历 todos
数组,并为每个元素生成一个模板的副本,同时将当前元素作为 todo
变量传递给模板。