vue3-组合式api-watch,watchEffect
<template>
<div>
{{ counter }}
<button @click="changeCounter">改变counter</button>
<br />
{{ user.name }}
<button @click="changeUserName">改变名字</button>
<br />
</div>
</template>
<script>
import { ref, reactive, watch, watchEffect } from "vue";
export default {
setup() {
//counter逻辑代码
let counter = ref(0);
function changeCounter() {
counter.value++;
}
watch(counter, (newVal, oldVal) => {
console.log("newVal", newVal);
console.log("oldVal", oldVal);
});
//user逻辑代码
let user = reactive({
name: "张三",
age: 18,
});
function changeUserName() {
user.name = "李四";
}
//监听对象新值旧值一样
watch(
user,
(newVal, oldVal) => {
console.log("newVal", newVal);
console.log("oldVal", oldVal);
},
{
immediate: true, //立即执行 页面初始化的时候就执行
deep: true, //deep深度监听对象 但是新值旧值一样
}
);
//监听对象的属性 新旧值不一样
watch(
() => user.name,
(newVal, oldVal) => {
console.log("userNameNewVal", newVal);
console.log("userNameOldVal", oldVal);
}
);
//watchEffect回调函数,注意不需要指定监听属性,组件初始化的时候会执行一次回调函数,自动收集依赖
watchEffect(() => {
console.log(user.name);
});
return {
counter,
changeCounter,
user,
changeUserName,
};
},
};
</script>
运行效果:
点击改变counter按钮 输出
newVal 1
oldVal 0
点击改变名字按钮 输出
出 处:https://www.cnblogs.com/xiao-wo-niu/
版权声明:本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接。