vue3+pinia使用的时候,并没有对state
赋值,watch为什么还能监听到变化?
如果不用mapState
,第一次也监听不到,问题就在computed
和mapState
,为什么会出现这种情况?
//strore
import { defineStore } from "pinia"
const useTestStore = defineStore({
id: 'testStore',
state() {
return {
obj: {
name: '张三'
}
}
},
})
export default useTestStore
import useTestStore from "./store"
export default {
computed: {
...mapState(useTestStore, ['obj'])
},
watch: {
obj: {
handler(newValue, oldValue) {
//这里为什么会执行?
console.log('sss', JSON.stringify(newValue), JSON.stringify(oldValue))
},
deep: true
}
},
}
Pinia的store中的state是通过返回一个函数来初始化的,这个函数返回的对象是响应式的。当你在组件中使用watch来监听store的状态时,实际上是在监听这个响应式对象的变化。因为这个对象是响应式的,所以当它的任何属性发生变化时,Vue的响应式系统会自动触发watch的回调函数。