1. 安装pinia
yarn add pinia
# or with npm
npm install pinia
2. 安装持久化插件
# yarn
yarn add pinia-plugin-persistedstate
#pnpm
pnpm add pinia-plugin-persistedstate
#npm
npm install pinia-plugin-persistedstate
3. 创建store
首先创建store/index.js
# store/index.js
import { createPinia } from 'pinia';
import { createPersistedState } from 'pinia-plugin-persistedstate';
const pinia = createPinia();
pinia.use(createPersistedState({
storage: sessionStorage,
}));
export default pinia;
4. 引入pinia
main.js引入pinia
# main.js
import pinia from './store';
const app = createApp(App)
app.use(pinia)
5. 定义defineStore模块
pinia天生的模块化,可以直接定义,设置想要的模块名
定义一个set模块,只需defineStore第一个参数设置就行
import { defineStore } from 'pinia';
export const useSetStore = defineStore('set', {
state: () => ({
count: 1,
}),
getters: {
doubleCount: (state) => state.count * 2,
},
actions: {
increment() {
this.count++;
},
},
persist: true, // 设置持久化
// 单独设置存储位置
// persist: {
// storage: window.localStorage,
// },
});
5. 文件中使用
<template>
<div>
{{ store.count }}
</div>
</template>
<script setup>
import { storeToRefs } from 'pinia';
import { useSetStore } from './useSetStore';
const store = useSetStore();
</script>
如果想直接使用定义的state,以及getters中的参数,可以使用解构方式
如果直接使用解构,会失去响应式, 像这种
const { count } = useSetStore();
// 如果这样使用,视图引用的时候是不更新的
我们要用storeToRefs, 直接使用,而且也是响应式的
<template>
<div>
{{ count }}
</div>
<button @click="clickHandle">add count</button>
</template>
<script setup>
import { storeToRefs } from 'pinia';
import { useSetStore } from './useSetStore';
const store = useSetStore();
const { count } = storeToRefs(store);
const clickHandle = () => {
store.increment();
};
</script>
6. 不同模块之间使用
创建home模块
// home/useHomeStore.js
import { defineStore } from 'pinia';
export const useHomeStore = defineStore('home', {
state: () => ({
length: 1,
}),
getters: {
doubleLength: (state) => state.length * 2,
},
actions: {
add() {
this.length++;
},
},
});
在set模块中使用
import { defineStore } from 'pinia';
import { useHomeStore } from '../home/useHomeStore';
const homeStore = useHomeStore();
export const useSetStore = defineStore('set', {
state: () => ({
count: 1,
}),
getters: {
doubleCount: (state) => state.count * 2,
},
actions: {
increment() {
homeStore.add();
this.count++;
},
},
});
7. 其他API
这里就说几个常用的,其他的自己自行搜索
-
$id:id 模块的唯一标识
-
$dispose ():void
停止存储关联的模块,并删除当前模块,devetools插件也停止显示该模块
备注:数据还是可以正常使用,不受影响(测试结果)使用前:可以看到有两个模块
调用$dispose方法,可以看到devetools插件已经不再显示该模块
-
$onAction ( callback, detached?): () =>void
如果detached不设置true,组件卸载的时候自动清除 设置每次将要调用操作时调用的回调。回调接收一个对象:
-
store: 调用它的商店
-
name: 动作名称
-
args: 传递给动作的参数
-
after after回调
-
onError 报错回调
-
store.$onAction(({
after, name, args, onError, store,
}) => {
console.log('name, args, store: ', name, args, store);
after((resolvedValue) => {
console.log('resolvedValue: ', resolvedValue);
});
onError((error) => {
console.log('error: ', error);
});
});
-
$patch ( partialState):void
上面👆🏻已经用过, 调用该方法同步设置state里的值 -
$reset ():void
通过构建新的状态对象将存储重置为其初始状态 这个方法就比较有用了,如果我们的逻辑处理完了,调用该方法,可以重置该模块下的所有的数据