首先搭建vue3 vite 项目
npm create vue
选择pinia 或者自己安装pinia
自己安装需要
npm install pinia
并在main.js中挂在上:
const pinia = createPinia()
const app = createApp(App)
app.use(pinia)
app.mount('#app')
创建stores文件夹和counter.js文件
counter.js中的内容如下:
import { ref, computed } from 'vue'
import { defineStore } from 'pinia'
export const useCounterStore = defineStore('counter', () => {
const count = ref(0)
const other_counts = ref(0)
const doubleCount = computed(() => count.value * 2)
function increment() {
count.value++
console.log(count.value)
}
// 分别设置不同的计时器
setInterval(()=>{
count.value = count.value+1
},1000)
// 分别设置不同的计时器
setInterval(()=>{
other_counts.value = other_counts.value+1
}, 3000)
// 一定要返回 count, other_counts 不然监听不到
return { count, other_counts, doubleCount, increment }
})
在app.vue中进行监听,内容如下:
import {watch} from "vue";
import {useCounterStore} from "@/stores/counter.js";
const counter_store = useCounterStore()
// 单独监听store中的某一个属性
watch(()=>counter_store.count, (new_data, old_data)=>{
console.log("watch", old_data, new_data)
})
// // 监听 store 的状态变化, 即监听store中的所有属性的变化
counter_store.$subscribe((mutation, state) => {
console.log("state.count", state.count)
console.log("state.other_counts", state.other_counts)
});
页面打印结果如下:
watch 0 1
state.count 1
state.other_counts 0
watch 1 2
state.count 2
state.other_counts 0
watch 2 3
state.count 3
state.other_counts 0
state.count 3 // 这次输出的3 是因为other_counts的状态发生了变化才输出state.count
state.other_counts 1
watch 3 4
state.count 4
state.other_counts 1
打印结果分析:
watch监听到store中某一个属性变化后会立即响应,$subscribe方式会监听整个store中的所有属性是否变化,任何一个变化,都会调用$subscribe里的回调函数
$subscribe 也可以这样写:
import {watch} from "vue";
import {useCounterStore} from "@/stores/counter.js";
const counter_store = useCounterStore()
// watch(()=>counter_store.count, (new_data, old_data)=>{
// console.log("watch", old_data, new_data)
// })
// const websocketMsessage = computed(() => websocketMsessageStore.websocketMsessage);
// // 监听 store 的状态变化
counter_store.$subscribe((mutation, {other_counts}) => {
// console.log("state.count", state.count)
console.log("state.other_counts",other_counts)
});
打印结果如下:
再次说明了$subscribe只要监听到store中任何字段的变化都会执行其回调函数