Pinia 是新一代的状态管理器,由 Vue.js团队中成员所开发的,因此也被认为是下一代的 Vuex,即 Vuex5.x,尤雨溪推荐在vue3项目中替代Vuex。
1、对 typescript 兼容性更好;
2、去除 mutations,只有 state,getters,actions;
3、修改状态可以直接修改,也可以在action中修改;
4、actions中 支持使用同步和异步;
5、更加小巧,压缩后的体积只有1.6kb;
6、可以创建多个store;
一、安装
npm i pinia --save-dev
二、使用
1、挂载
import { createPinia } from 'pinia';
const pinia = createPinia();
app.use(pinia);
app.mount('#app')
2、创建store
store/index.js
import { defineStore } from "pinia"
/**
* 这个 第一个参数main,也称为 id,是必要的,Pinia 使用它来将 store 连接到 devtools。
* 将返回的函数命名为use...(更好的语义化) 是跨可组合项的约定,以使其符合你的使用习惯。
*/
export const useStore = defineStore('main', {
state: () => {
return {
count: 0,
list: [1, 2, 3, 4 ]
}
},
/**
* 用来封装计算属性 有缓存功能 类似于computed
*/
getters: {
getNum(state){
return `我是一个计数器${state.count}`
}
//或者不使用state传递参数直接使用this
//getNum(){
// return `我是一个计数器${this.count}`
// }
},
/**
* 编辑业务逻辑 类似于methods
*/
actions: {
changeState(){
this.count = 123;
}
}
})
3、使用store
<template>
{{ store.count }}
</template>
import { useStore } from '@/store/index.js'
const store = useStore();
4、使用getters
Pinia中的 getters 与vue中的getter同为计算属性,具有缓存性,如果getters中的属性值未发生变化,多次调用只执行一次
store/index.js
getters: {
getNum(){
return ` 计数 ${this.count} `
}
},
<template>
{{ store.getNum }}
</template>
getters传值
使用getters组件中可以传递参数
<div>{{store.getters 函数名(参数)}}</div>
在store里边找到对应的getters函数
getters:{
getters函数名(state){
return (形参)=>{
执行代码
}
}
}
5、调用store里边的actions
store.actions 方法名()
actions传值
在actions里接收一个形参
actions:{
actions函数参数名(形参){
}
}
在组件中传递实参
store.actions函数名(实参)