Vue2解决pinia刷新后数据丢失的问题

Pinia:官网

Pinia 是一个 Vue.js 状态管理库,如果你在组件中修改了 store 中的数据并刷新了界面,Pinia 会将 store 中的数据重置为初始值,从而导致数据丢失的问题。

这里给出vue2的解决方案:

可以使用 Pinia 的 Persist 插件,该插件可以将 Pinia 的 store 数据持久化到本地存储中,这样当你刷新页面时,store 中的数据不会丢失。可以参考文档:文档

安装Persist ,选择你喜欢的包管理器

# yarn
yarn add pinia-plugin-persist
# npm
npm install pinia-plugin-persist

main.js文件

import { createPinia, PiniaVuePlugin } from 'pinia' //vue2需要引入PiniaVuePlugin 
import piniaPluginPersist from 'pinia-plugin-persist'//引入pinia数据持久化插件

Vue.use(PiniaVuePlugin)
const pinia = createPinia()//创建pinia的实例
pinia.use(piniaPluginPersist);

new Vue({
  router,
  render: h => h(App),
  pinia,
}).$mount('#app')

 articeId.js,这里我是保存文章Id,所以是这个文件,根据官方文档,在src/stores下创建该文件

import { defineStore } from 'pinia'

// 你可以对 `defineStore()` 的返回值进行任意命名,但最好使用 store 的名字,同时以 `use` 开头且以 `Store` 结尾。(比如 `useUserStore`,`useCartStore`,`useProductStore`)
// 第一个参数是你的应用中 Store 的唯一 ID。
export const useArticleIdsStore = defineStore('articleId', {
  // 其他配置...
  persist: {
    enabled: true,//开启数据持久化
    strategies: [
      {
        key: 'articleId',//给一个要保存的名称
        storage: localStorage,// localStorage 存储方式为本地存储
      }
    ]
  },
  state:()=>{
    //需要保存的数据,初始值为0
    return {articleId:0}
  },
  actions:{

  }
})

使用样例:

import { useArticleIdsStore } from '@/stores/articleId'
const articleIdsStore = useArticleIdsStore();
    methods: {
        getArticle() {
            //获取存储的articleId值
             const articleId = articleIdsStore.articleId;
            //其他操作...
        }, 
    },

你可能感兴趣的:(web学习总结,学习,JavaWeb,pinia)