安装 npm install pinia
注册
初始化仓库
可以新建一个文件 store, 里面建一个 index.ts, 一个store-name.ts 用于放置命名空间
defineStore 的第一个参数也称为id,是必要的,Pania 使用它连接到 devtools。将返回的函数命名为 use... 是可组合项之间的约定,以使其使用习惯。
组件中简单使用state的值
五种方式修改state里面的值
pinia解构
正常解构的话 解构出来的值不具有响应式
要解构是响应式的 就要引入 storeToRefs 用它包裹一下 就是响应式的了
actions使用 同步 代码修改 state里面的值
actions里面的方法 可以相互调用
getters的使用
.使用箭头函数不能使用this this指向已经改变指向undefined 修改值请用state
主要作用类似于computed 数据修饰并且有缓存
getters:{
newPrice:(state)=> `$${state.user.price}`
},
2.普通函数形式可以使用this
getters:{
newCurrent ():number {
return ++this.current
}
},
3.getters 互相调用
getters:{
newCurrent ():number | string {
return ++this.current + this.newName
},
newName ():string {
return `$-${this.name}`
}
}
pinia 数据持久化
安装 插件 npm install pinia-persistedstate-plugin --save
// 哪一个模块要用 就把下面的配置放进去
persist: {
enabled: true,
strategies: [
{
// key的名称
key: "my_shop",
// 更改默认存储,改为localStorage
storage: localStorage,
// 默认是全部进去存储
// 可以选择哪些进入local存储,这样就不用全部都进去存储了
paths: ["list"],
},
],
},