环境:
vue 3.x
为了在多个页面中共享数据状态。 欲使用pinia进行状态管理。 以下是使用例子。
使用步骤
1、创建store
文件目录: src/stores/notify.js
import { ref, computed } from 'vue'
import { defineStore } from 'pinia'
export const useNotifyStore = defineStore('notify', {
state: () => ({ notifyType: "closed",title:"", content: "" }),
getters: {
getNotifyType: (state) => state.notifyType,
},
actions: {
setNotifyType(val) {
this.notifyType = val;
},
setContent(val) {
this.content = val;
}
},
})
2、vue组件使用store
2.1 引入store
import { useNotifyStore } from "@/stores/notify";
export default {
setup() {
const notifyStore = useNotifyStore();
return { notifyStore }
},
created() {},
...
此处使用setup的写法, 是因为组件未采用Vue 组合式 API 的写法。 有关Vue 组合式 API写法,请参考官网介绍。
2.2 访问store的值
console.log(this.notifyStore.notifyType)
2.3 修改值
this.notifyStore.$patch((state) => {
state.notifyType = "progress";
state.content = "";
state.title = "文字识别";
});
2.4 watch store的state 变化
watch: {
"notifyStore.$state": {
handler(newV) {
if(newV.notifyType == "progress" || newV.notifyType == "result") {
this.notify.isActive = true;
this.notify.title = newV.title;
this.notify.content = newV.content;
}
},
deep: true
}
},
$state是notifyStore对象的一个属性。(通过console.log(this.notifyStore)方法可以查看)。
查看 对象 的属性:
for(let k in obj) {
console.log(k, obj[k])
}
以上为个人在实际使用的例子。 作为笔记记录吧。
有关pinia更多的介绍请参考官网。