Vue3中使用pinia实现状态管理的知识与操作

116 阅读1分钟

什么是pinia

pinia是Pinia 是一个基于 Vue.js 的状态管理库,用于管理应用程序的数据。相较于Vuex,使用pinia进行数据的管理更加高效简洁,使管理数据的实现更加轻量化,且对Typescript的支持更好。

实现数据的状态管理的操作

1、创建存放存放数据的仓库

export const useUserStore = defineStore('user', {
    state: () => {
        return {               
                name: "curry",
                age: 35,            //声明数据
        };
    }              

此处'user'即为这个仓库的名字,state 是一个返回初始状态的函数访问state时, 使用定义的 store 实例就可以直接对其 state 进行读写,例如此处

const userStore = useUserStore()
userStore.name   //即可对name进行读写操作

对仓库中的数据进行更改处理

若集中更改所有数据,可以调用实例的$patch方法,例如

  userStore.$patch({
      count:userStore.count + 1,
      name: '',
})

若重置state中所有数据,即返回state默认状态,可以调用实例的$reset方法

userStore.$reset()

getters

getter 是 state 的计算值,它将接收state 作为第一个参数。
在 getter 中可以使用 this 访问到整个 store 实例

getters: {
        // 类似于computed计算属性,
        doubleAge(state) {
            return state.age * 2
        },
        //在getter中 使用另一个getter  this指向当前存储库
        addOneAge() {
            return this.doubleAge + 1
        }

直接在 store 实例上访问 getter中的方法即可,例如

const userStore = useCountStore () 
    // state 中的默认age是1
userStore.doubleCount //2 
userStore.doublePlusOne // 3

actions

action 类似于组件的 methods,可以执行异步操作,处理业务逻辑

actions: {
    modifyAge(val) {
        this.age = val < 5 ? val : 0 // val小于5则赋值val否则赋值0 } 
        }
    }    

直接用store实例调用actions中的方法

const store = useDemoStore()
let count = ref(0)
store.modifyCount(count.value)