解决pinia刷新数据消失,实现持久化存储

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;
});

刷新测试是否数据是否消失

在浏览器可以看到存储数据

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值