vue2
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| <template> <h2>{{ message }}</h2> <button @click="info.name = 'kkk'">修改message</button> <button @click="info.friends.name = 'oooo'">修改message</button> </template>
<script> export default { data() { return { info: { name: "ddd", friends: { name: "ppp" }, }, }; }, watch: { info: { handler: (newValue, oldvalue) => { console.log(newValue, oldvalue); }, immediate: true, deep: true, }, }, }; </script>
|
vue3
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
| <template> <h2>{{ message }}</h2> <button @click="message = 'ooo'">修改message</button> <button @click="info.name = 'ooo'">修改message</button> <button @click="info.friends.name = 'james'">修改message</button> </template>
<script setup> import { ref, watch, reactive } from "vue"; const message = ref("hello"); const info = reactive({ name: "hh", friends: { name: "jack" }, }); watch(message, (newValue, oldValue) => { console.log(newValue, oldValue); });
watch(info, (newValue, oldValue) => { console.log(newValue, oldValue); });
watch( () => ({ ...info }), (newValue, oldValue) => { console.log(newValue, oldValue); }, { deep: true, immediate: true } ); </script>
|
watchEffect
watchEffect 会自动收集依赖,依赖改变,就会执行函数
1 2 3 4 5
| const counter = ref(0); watchEffect(() => { console.log(counter.value); }); </script>
|
停止监听
1 2 3 4 5 6 7 8
| const counter = ref(0); const stopWatch = watchEffect(() => { console.log(counter.value);
if (counter.value > 5) { stopWatch(); } });
|