计算属性
<script setup>
import { ref,computed } from 'vue'
let id = 0
const newTodo = ref('')
const hideCompleted = ref(false)
const todos = ref([
{ id: id++, text: 'Learn HTML', done: true },
{ id: id++, text: 'Learn JavaScript', done: true },
{ id: id++, text: 'Learn Vue', done: false }
])
const filteredTodos = computed(() => {
return hideCompleted.value
? todos.value.filter((t) => !t.done)
: todos.value
})
function addTodo() {
todos.value.push({ id: id++, text: newTodo.value, done: false })
newTodo.value = ''
}
function removeTodo(todo) {
todos.value = todos.value.filter((t) => t !== 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 filteredTodos" :key="todo.id">
<input type="checkbox" v-model="todo.done">
<span :class="{ done: todo.done }">{{ todo.text }}</span>
<button @click="removeTodo(todo)">X</button>
</li>
</ul>
<button @click="hideCompleted = !hideCompleted">
{{ hideCompleted ? 'Show all' : 'Hide completed' }}
</button>
</template>
<style>
.done {
text-decoration: line-through;
}
</style>hideCompleted
示例代码中,给每一个todo添加了切换功能,通过在数组中给每一个todo添加一个done属性实现,并使用v-model将该属性双向绑定到复选框上,通过点击复选框实现切换done值。并通过:class获取删除线的样式并作用与todo上。
底部添加了一个可以切换hideCompleted状态的按钮,我们要基于hideCompleted的状态实现不同的渲染效果:隐藏done为true的todo,或显示全部todo。
介绍API:computed()可以创建一个计算属性ref,这个ref会动态的根据其他响应式数据源计算其.value值。计算属性会自动跟踪其计算中所使用的其他响应式状态,并收集为自己的依赖,而计算结果被缓存,当依赖发生改变时,才会自动更新。
因为我们希望v-for渲染的是计算筛选过后的列表,所以不再in todos,而是in filteredTodos,在filteredTodos中,需要返回过滤后的列表,并可以通过按钮选择切换显示过滤或显示全部,所以通过正则表达式:
hideCompleted.value ? todos.value.filter((t) => !t.done) : todos.value
表示当hideCompleted为true时显示done为true的所有todo的列表,当hideCompleted为false时显示默认列表。
当点击底部button时,@click="hideCompleted = !hideCompleted"使hideCompleted的值(true/false)切换,同时触发computed(),从而实现在需要时隐藏已完成的todo。
评论区