现在有没有免费的网站,网站页面制作公司,模板网恋,北海网站建设Pinia#xff1a;官网
Pinia 是一个 Vue.js 状态管理库#xff0c;如果你在组件中修改了 store 中的数据并刷新了界面#xff0c;Pinia 会将 store 中的数据重置为初始值#xff0c;从而导致数据丢失的问题。
这里给出vue2的解决方案#xff1a;
可以使用 Pinia 的 Per…
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 结尾。(比如 useUserStoreuseCartStoreuseProductStore)
// 第一个参数是你的应用中 Store 的唯一 ID。
export const useArticleIdsStore defineStore(articleId, {// 其他配置...persist: {enabled: true,//开启数据持久化strategies: [{key: articleId,//给一个要保存的名称storage: localStorage,// localStorage 存储方式为本地存储}]},state:(){//需要保存的数据初始值为0return {articleId:0}},actions:{}
})
使用样例
import { useArticleIdsStore } from /stores/articleId
const articleIdsStore useArticleIdsStore();methods: {getArticle() {//获取存储的articleId值const articleId articleIdsStore.articleId;//其他操作...}, },