pinia全局状态管理的使用

598 阅读1分钟

vue中使用pinia

image-20230309090558011.png

​ 全局状态管理,作用是为了代替Vuex.

  1. 完整的ts支持
  2. 轻量,压缩体积较小1kb
  3. 去除了Vuex中的mutations ,只有state,getters和actions
  4. action同时支持同步和异步
  5. 没有模块嵌套,互相使用 每个store是独立的
  6. 支持vue2和vue3

一、安装pinia

npm install pinia -S

二、引入pinia

//vue2 main.ts中
import {PiniaVuePlugin} from 'pinia'
const store = PiniaVuePlugin()
const app = createApp()
app.use(store)
//vue3 main.ts中
import {createPinia} from 'pinia'
const store = createPinia()
const app = createApp()
app.use(store)

三、创建store仓库

​ 在src目录下创建文件store/index.ts

//引入pinia定义存储
import {defineStore} from 'pinia'

export const Test = defineStore(
  'A',
  {
  state:()=>{
    return  {
      current:1,
      name:''
    }
  },
  getters:{
      //类似computed
  },
  actions:{
    //同步异步操作都可
  }
})

四、使用state、getters、actions

1.state值修改


import {Test} from '@/store'
const test = Test()
//第一种方式 直接使用
test.current++
//第二种方式 批量修改
test.$patch({
	current:4444,
    name:'wawa'
})
//第三种方式 推荐使用这种函数的方式 得传入state参数
//暂且不知道为啥用patch()
test.$patch((state)=>{
    state.current = 6666
    state.name = 'aaaa'
})
//第四种方式
test.$state ={current:3000,name:'hahah'}

//第五种方式
test.setCurrent()
///解构store 不具有响应式 需要storeToRefs 源码里先变原始对象 防止重复引用
const {current,name} = storeToRefs(test)
//actions中使用
actions:{
    //不能用箭头函数
    //setCurrent:()=>{}
    setCurrent(){
    this.current++
}

2.getters使用

//与computed类似 依赖缓存 要返回数据时用
getters:{
    newName():string{
        return `$-${this.name}`
	}
}

3.actions使用

//可以写同步,也可以写异步 方法直接可以相互调用
//1.actions中使用 同步写法
actions:{
    //不能用箭头函数
    //setCurrent:()=>{}
    setCurrent(){
    this.current++
  //异步写法
     async set(){
         const result = await Login()
         this.setCurrent()
	}
}

五、API

//$reset 数据重置为原始值 
test.$reset()
//$subscribe //可以获取到test实例 写插件可以用
test.$subscribe((args,state)=>{
},{
   deep:true//等等 
})
//$onAction 
test.$onAction((args)=>{
    console.log(args)
})