Vue2中pinia刷新后數(shù)據(jù)丟失的問題解決
Pinia:官網(wǎng)
Pinia 是一個 Vue.js 狀態(tài)管理庫,如果你在組件中修改了 store 中的數(shù)據(jù)并刷新了界面,Pinia 會將 store 中的數(shù)據(jù)重置為初始值,從而導(dǎo)致數(shù)據(jù)丟失的問題。
這里給出vue2的解決方案:
可以使用 Pinia 的 Persist
插件,該插件可以將 Pinia 的 store 數(shù)據(jù)持久化到本地存儲中,這樣當(dāng)你刷新頁面時,store 中的數(shù)據(jù)不會丟失??梢詤⒖嘉臋n:文檔
安裝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數(shù)據(jù)持久化插件 Vue.use(PiniaVuePlugin) const pinia = createPinia()//創(chuàng)建pinia的實(shí)例 pinia.use(piniaPluginPersist); new Vue({ router, render: h => h(App), pinia, }).$mount('#app')
articeId.js,這里我是保存文章Id,所以是這個文件,根據(jù)官方文檔,在src/stores下創(chuàng)建該文件
import { defineStore } from 'pinia' // 你可以對 `defineStore()` 的返回值進(jìn)行任意命名,但最好使用 store 的名字,同時以 `use` 開頭且以 `Store` 結(jié)尾。(比如 `useUserStore`,`useCartStore`,`useProductStore`) // 第一個參數(shù)是你的應(yīng)用中 Store 的唯一 ID。 export const useArticleIdsStore = defineStore('articleId', { // 其他配置... persist: { enabled: true,//開啟數(shù)據(jù)持久化 strategies: [ { key: 'articleId',//給一個要保存的名稱 storage: localStorage,// localStorage 存儲方式為本地存儲 } ] }, state:()=>{ //需要保存的數(shù)據(jù),初始值為0 return {articleId:0} }, actions:{ } })
使用樣例:
import { useArticleIdsStore } from '@/stores/articleId' const articleIdsStore = useArticleIdsStore();
methods: { getArticle() { //獲取存儲的articleId值 const articleId = articleIdsStore.articleId; //其他操作... }, },
到此這篇關(guān)于Vue2中pinia刷新后數(shù)據(jù)丟失的問題解決的文章就介紹到這了,更多相關(guān)Vue2 pinia刷新后數(shù)據(jù)丟失內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
詳解auto-vue-file:一個自動創(chuàng)建vue組件的包
這篇文章主要介紹了auto-vue-file:一個自動創(chuàng)建vue組件的包,需要的朋友可以參考下2019-04-04vue+element table表格實(shí)現(xiàn)動態(tài)列篩選的示例代碼
這篇文章主要介紹了vue+element table表格實(shí)現(xiàn)動態(tài)列篩選的示例代碼,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-01-01vue3實(shí)現(xiàn)國際化的過程與遇到的問題詳解
像很多大型的網(wǎng)址,特別是跨國際等公司網(wǎng)頁,訪問來自世界各地用戶,所以網(wǎng)頁的國際化極其重要的需求,這篇文章主要給大家介紹了關(guān)于vue3實(shí)現(xiàn)國際化的過程與遇到的問題的相關(guān)資料,需要的朋友可以參考下2022-05-05