分类目录: html5
vue3的watch和watchEffect和computed
Post date:
Author: cyy
标签: vue3
Number of comments: no comments
vue3的watch和watchEffect的区别:
- watch 是需要传入侦听的数据源,而 watchEffect 是自动收集数据源作为依赖。
- watch 可以访问侦听状态变化前后的值,而 watchEffect 没有,watchEffect获取的改变后的值。
- watch 是属性改变的时候执行,当然也可以immediate,而 watchEffect 是默认会执行一次(相当于自带 immediate),然后属性改变也会执行。
例:
<template>
<section>
<div>num:{{ num }}</div>
<div>num2:{{ num2 }}</div>
<button @click="addNum">addNum</button>
</section>
</template>
<script>
import { ref, watch, watchEffect } from "vue";
export default {
setup() {
const num = ref(1);
const num2 = ref(1);
const addNum = () => {
num.value++;
num2.value++;
};
watch(() => num.value, (newValue, oldValue) => {
console.log(`num新值为${newValue}`);
});
watchEffect(() => {
console.log(`num2新值为${num2.value}`);
});
return {
num,
num2,
addNum,
};
},
};
</script>
<style lang="scss">
</style>
watch监听多个值:
<template>
<section>
<div>num:{{ num }}</div>
<div>num2:{{ num2 }}</div>
<button @click="addNum">addNum</button>
</section>
</template>
<script>
import { ref, watch } from "vue";
export default {
setup() {
const num = ref(1);
const num2 = ref(1);
const addNum = () => {
num.value++;
num2.value++;
};
// wahcth多个
watch(
() => [num.value, num2.value],
([newNum1, newNum2], [oldNum1, oldNum2]) => {
console.log(`num1新值为${newNum1}`);
console.log(`num2新值为${newNum2}`);
console.log(`num1旧值为${oldNum1}`);
console.log(`num2旧值为${oldNum2}`);
}
);
return {
num,
num2,
addNum,
};
},
};
</script>
<style lang="scss">
</style>
computed:
<template>
<section>
<div>num:{{ num }}</div>
<div>num2:{{ num2 }}</div>
<div>sum:{{ sum }}</div>
<button @click="addNum">addNum</button>
</section>
</template>
<script>
import { ref, computed } from "vue";
export default {
setup() {
const num = ref(1);
const num2 = ref(1);
const addNum = () => {
num.value++;
num2.value++;
};
const sum = computed(() => num.value + num2.value);
const sum2 = computed({
// 取值函数
get: () => (num.value + 1),
// 赋值函数
set: val => {
num.value = val - 1
}
})
return {
num,
num2,
sum,
sum2,
addNum,
};
},
};
</script>
<style lang="scss">
</style>