1.下载插件
npm install pinia-plugin-persist
2.配置store/index.js文件
import { createPinia } from 'pinia';
import piniaPluginPersist from 'pinia-plugin-persist';
const store = createPinia()
store.use(piniaPluginPersist);
export default store
3.在需要实现持久化存储的module中添加持久化配置
我这里的路径是store/modules/order.js
const useOrderStore = defineStore('order', {
state: () => {
return {
todoOrderNum: 0,//待办数量
}
},
actions: {
setTodoOrderNum(total) {
this.todoOrderNum = total
}
},
persist: {
enabled: true,//开启持久化存储
}
}
)
export default useOrderStore
4.页面中使用
调用方法赋值
import useOrderStore from "@/store/modules/order";
const orderStore = useOrderStore();
const getTodoOrderTotal = () => {
toDoOrderTotal().then((res) => {
orderStore.setTodoOrderNum(res.data);
});
};
getTodoOrderTotal();
公共使用页面
import useOrderStore from "@/store/modules/order";
const orderStore = useOrderStore();
onMounted(() => {
orderTotals.value = orderStore.toDoOrderTotal;
});
刷新测试是否数据是否消失
在浏览器可以看到存储数据