todos.value.filter((t) => t !== todo)
(t) => t !== todo实际上就是
function(t){
return t !==todo
}
- t是一个形参,不用考虑他的具体意义,它可以是a,也可以是b…
- 这段代码是JavaScript中的数组方法filter()的应用。它的作用是从数组this.todos中筛选出所有不等于传入参数todo的元素,并返回一个新的数组。具体来说,箭头函数(t) => t !== todo表示对于数组中的每一个元素t,只有当t不等于传入的参数todo时,才将其保留在新数组中。这个方法不会改变原数组,而是返回一个新的数组。
// 举例说明
let arr = [1, 2, 3, 4, 5];
let arr_new
let remove = 3;
arr_new = arr.filter((item) => item !== remove);
console.log(arr); // 输出 [1, 2, 3, 4, 5]
console.log(arr_new); // 输出 [1, 2, 4, 5]
let arr2 = [1, 2, 3, 4, 5];
let remove2 = [1, 2, 3];
arr2 = arr2.filter((item) => !remove2.includes(item));
console.log(arr2); // 输出:[4,5]
JavaScript 数组filter方法完整介绍:http://t.csdn.cn/9Ho6q
做vue官方教程看见的,作为初学者一脸懵:https://cn.vuejs.org/tutorial/#step-7
<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() {
todos.value.push({ id: id++, text: newTodo.value })
newTodo.value = ''
}
function removeTodo(todo) {
todos.value = todos.value.filter((t) => t !== todo)
}
</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>