vue3之watch和computed方法:
1.computed相关
ex1:
const isLoggedIn = computed(() => status.value === "authenticated"); // 这种对于简单操作是很方便的
ex2:
const isLoggedIn = computed(() => {
return status.value === "authenticated"; // 对于复杂的逻辑操作还是通过完整的方法体处理
});
ex3:默认情况下,计算属性仅为 getter(如上面的两种使用方式,其实都是getter的简写调用方式)。如果试图为计算属性赋新值,可以通过提供一个 getter 和一个 setter 来创建计算属性:
<script setup>
import { ref, computed } from 'vue'
const firstName = ref('John')
const lastName = ref('Doe')
const fullName = computed({
// getter
get() {
return firstName.value + ' ' + lastName.value
},
// setter
set(newValue) {
// Note: we are using destructuring assignment syntax here.
[firstName.value, lastName.value] = newValue.split(' ')
}
})
</script>
现在,当运行 fullName.value = 'Jerry Tom'时,setter 将被调用,firstName 和 lastName 也会相应更新。
computed 返回值是一个 computed ref, s所以这里可以使用 isLoggedIn.value,还有很重要一点,computed 中使用的属性应该是 reactive(ref) 的,这个和vue2不一样,原因在于 vue3 使用了大量组合式API.
重要的是要记住,计算型获取函数只能执行纯粹的计算,不能有任何副作用。例如,不要在计算型获取函数中更改其他状态、进行异步请求或更改 DOM!将计算属性视为声明性地描述如何根据其他值推导出一个值,它唯一的职责就是计算并返回该值.
计算属性的返回值是派生状态。把它想象成一个临时快照--每次源状态发生变化,就会创建一个新的快照。更改快照是没有意义的,因此计算的返回值应被视为只读,绝不能更改,而应更新它所依赖的源状态,以触发新的计算.
参考: https://vuejs.org/guide/essentials/computed.html
2.watch相关:
watch's first argument can be different types of reactive "sources": it can be a ref (including computed refs), a reactive object, a getter function, or an array of multiple sources, 第二个参数是一个 callback.
ex:
const x = ref(0)
const y = ref(0)
// single ref
watch(x, (newX) => {
console.log(`x is ${newX}`)
})
// getter
watch(
() => x.value + y.value,
(sum) => {
console.log(`sum of x + y is: ${sum}`)
}
)
// array of multiple sources
watch([x, () => y.value], ([newX, newY]) => {
console.log(`x is ${newX} and y is ${newY}`)
})
实际使用例子:
ex1:
watch(
() => isAdditionalFacetsExpanded.value,
(newVal) => {
if (!newVal) {
clearSearch();
abortByKey(ABORT_CONTROLLER_KEY);
} else {
loadData(); // 可以异步请求数据
}
}
);
ex2:
watch(
() => route.path,
() => {
headerNav.setMobileDrawerVisibility(false); // 修改 pinia 中的状态
}
);
ex3:
watch(
() => isMetricsError.value,
() => {
error.value = isMetricsError.value;
},
{
immediate: true,
}
);
ex4:
watch(
source,
(newValue, oldValue) => {
// when `source` changes, triggers only once
},
{ once: true }
)
watch 默认是 "懒惰 "的:在被监视源发生变化之前不会调用回调。但在某些情况下,我们可能希望紧急运行相同的回调逻辑,例如,我们可能希望获取一些初始数据,然后在相关状态发生变化时重新获取数据. 我们可以通过传递 immediate: true 选项来强制立即执行观察者的回调.
watch 默认只要被监视源发生变化,监视器的回调就会执行。如果希望回调只在源更改时触发一次,请使用 once: true 选项.
参考: https://vuejs.org/guide/essentials/watchers.html
