<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 nTodo = ref({id: todos.value.length,text: newTodo.value})
todos.value.push(nTodo.value)
console.log(todos.value)
}
function removeTodo(todo) {
// ...
console.log(todo.id)
todos.value = todos.value.filter((todos) => todos.id != todo.id)
}
</script>
<template>
<form @submit.prevent="addTodo">
<input v-model="newTodo">
<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>
注意点:
1.vue中数组增加一列可以使用push()方法。todos.value.push(nTodo.value)
删除数组中的一列可以使用filter()方法,用箭头函数指明要删除对象的条件。todos.value.filter((todos) => todos.id != todo.id)
具体参照Vue实现删除数组中指定元素的方式