watch
<template>
<div class="watch">
<div>{{ message }}</div>
<h1>user: {{ user.name }} - {{ user.age }}</h1>
<button @click="user.name='李四'">监听变化</button>
</div>
</template>
<script>
import { reactive,watch } from "vue";
export default {
setup() {
const message = "why";
const user = reactive({
name: "张三",
age: 18,
});
// 监听当前对象
watch(user,(newValue,oldValue)=>{
console.log(newValue,oldValue);
console.log(newValue===oldValue);
})
// 1. 监听reactive数据变化后,获取普通对象
watch(()=>({...user}),(newValue,oldValue)=>{
console.log(newValue,oldValue);
})
return {
message,
user,
};
},
};
</script>
<style lang="less" scoped></style>
watchEffect
<template>
<div class="watch">
<h1>{{counter}}</h1>
<button @click="counter++">+1</button>
</div>
</template>
<script>
import { watchEffect,ref,watch } from "vue";
export default {
setup() {
const counter = ref(0)
// watch(counter,(newValue,oldValue)=>{
// console.log(newValue);
// })
// 1. watchEffect传入的函数默认直接被执行
// 2. 在执行的过程中,会自动的收集依赖(依赖哪些响应式数据)
const stopWatch = watchEffect(()=>{
console.log('---',counter.value);
// 当counter的值大于等于10的时候停止监听
if(counter.value >= 10){
stopWatch()
}
})
return {
counter
}
},
};
</script>
<style lang="less" scoped></style>