vue中使用pinia

环境:

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更多的介绍请参考官网。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值