计算属性computed
计算属性来描述依赖响应式状态的复杂逻辑
使用时需要引入 computed
<template><p>Has published books:</p><span>{{ publishedBooksMessage }}</span></template><script setup>import { reactive, computed } from 'vue'const author = reactive({name: 'John Doe',books: ['Vue 2 - Advanced Guide','Vue 3 - Basic Guide']})// 返回值为一个计算属性 refconst publishedBooksMessage = computed(() => {return author.books.length > 0 ? 'Yes' : 'No'})</script>
侦听器 watch
watch 的第一个参数可以是不同形式的“来源”:它可以是一个 ref (包括计算属性)、一个响应式对象、一个 getter函数、或多个来源组成的数组:
//首先要引入 watchimport { ref, watch } from 'vue'const x = ref(0)const y = ref(0)// 单个 refwatch(x, (newX) => {console.log(`x is ${newX}`)})// getter 函数watch(() => x.value + y.value,(sum) => {console.log(`sum of x + y is: ${sum}`)})// 多个来源组成的数组watch([x, () => y.value], ([newX, newY]) => {console.log(`x is ${newX} and y is ${newY}`)})
注意,你不能侦听响应式对象的 property,例如:
const obj = reactive({ count: 0 })// 这不起作用,因为你是向 watch() 传入了一个 numberwatch(obj.count, (count) => {console.log(`count is: ${count}`)})
用 getter 函数 可以解决这个问题
// 提供一个 getter 函数watch(() => obj.count,(count) => {console.log(`count is: ${count}`)})
