vue3中的watch和watchEffect
两种写法的区别是:
watch 需要你明确指定依赖的变量,才能做到监听效果。
而 watchEffect 会根据你使用的变量,自动的实现监听效果。
watch:
// Vue3 的写法
<template>
<div>{{ count }}</div>
<div>{{ anotherCount }}</div>
<button @click="onClick">
增加 1
</button>
</template>
<script setup>
import { ref, watch } from 'vue';
const count = ref(1);
const onClick = () => {
count.value += 1;
};
const anotherCount = ref(0);
// 注意这里
// 需要在这里,
// 明确指定依赖的是 count 这个变量
watch(count, (newValue) => {
anotherCount.value = newValue - 1;
})
</script>
watchEffect
// Vue3 的写法
<template>
<div>{{ count }}</div>
<div>{{ anotherCount }}</div>
<button @click="onClick">
增加 1
</button>
</template>
<script setup>
import { ref, watchEffect } from 'vue';
const count = ref(1);
const onClick = () => {
count.value += 1;
};
const anotherCount = ref(0);
// 注意这里
watchEffect(() => {
// 会自动根据 count.value 的变化,
// 触发下面的操作
anotherCount.value = count.value - 1;
})
</script>