vue3动态生成的watch不会自动清除
<!-- 目标组件html -->
<div>
{{ store.counter }}
<button @click="store.counter++">add</button>
<button @click="createWatch">watch</button>
</div>
// 目标组件js
const store = useCounterStore() // store是全局的一个响应式对象
const createWatch = () => {
console.log('按装watch')
watch(() => store.counter, () => {
console.log('触发了侦听')
})
}
我们现在目标组件安装了watch
然后再销毁目标组件 切换到消费组件 点击add按钮
<!-- 消费组件html -->
{{ store.counter }}
<button @click="store.counter++">add</button>
// 消费组件js
const store = useCounterStore()
可以看到依然一直触发 侦听器 说明侦听器没有被销毁
所以vue3中动态生成的watch不会自动清除 销毁组建的 时候需要注意清除