它可以让我们创建一个计算属性 ref,这个 ref 会动态地根据其他响应式数据源来计算其 .value
:
import {ref,computed} from 'vue'
const hideComplete=ref(false)
const todos=ref([
{ id:id++,text:'learn html',done:false },
{ id:id++,text:'learn css',done:true },
{ id:id++,text:'learn vue',done:false }
])
const fiterTodos = computed(()=>{
// 根据 todos.value & hideCompleted.value
// 返回过滤后的 todo 项目
}
下面是一个使用computed() API的例子:
<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) //当(!t.done)为true的时候才会返回对应的todo
: 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) //相当于function(t){return t!==todo}
}
</script>
<template>
<form @submit.prevent="addTodo">
<input v-model="newTodo">
<button>Add Todo</button>
</form>
<ul>
<li v-for="todo in filteredTodos" :key="todo.id">
<input type="checkbox" v-model="todo.done"> <!--表单绑定,勾上复选框,对应的todo.done会变成true,不勾上就是false-->
<span :class="{ done: todo.done }">{{ todo.text }}-{{todo.id}}</span>
<!--这里的[done:todo.done}只有当todo.done为true的时候对应的css样式才会被渲染-->
<button @click="removeTodo(todo)">delete</button>
</li>
</ul>
<button @click="hideCompleted = !hideCompleted">
<!--反复交换按钮的值-->
{{ hideCompleted ? 'Show all' : 'Hide completed' }}
</button>
</template>
<style>
.done {
text-decoration: line-through;
}
</style>
结果如图,当复选框被选中的时候css的才会被渲染,还可以隐藏已经选中的,或者展示全部的: