Vue2中pinia刷新后數(shù)據(jù)丟失的問題解決
Pinia:官網(wǎng)
Pinia 是一個 Vue.js 狀態(tài)管理庫,如果你在組件中修改了 store 中的數(shù)據(jù)并刷新了界面,Pinia 會將 store 中的數(shù)據(jù)重置為初始值,從而導致數(shù)據(jù)丟失的問題。
這里給出vue2的解決方案:
可以使用 Pinia 的 Persist 插件,該插件可以將 Pinia 的 store 數(shù)據(jù)持久化到本地存儲中,這樣當你刷新頁面時,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的實例
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()` 的返回值進行任意命名,但最好使用 store 的名字,同時以 `use` 開頭且以 `Store` 結(jié)尾。(比如 `useUserStore`,`useCartStore`,`useProductStore`)
// 第一個參數(shù)是你的應用中 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-04
vue+element table表格實現(xiàn)動態(tài)列篩選的示例代碼
這篇文章主要介紹了vue+element table表格實現(xiàn)動態(tài)列篩選的示例代碼,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2021-01-01

