vue 項目中如何在頁面刷新的狀態下保留數據


 1.問題:在vue項目中,刷新頁面之后,我當前打開的所有菜單,都消失,我如何實現刷新之后頁面仍然是刷新之前的狀態

  效果圖:

解決方法: 

  使用vuex作狀態管理: 將vuex里面的數據同步更新到localStorage里面,改變vuex里的數據,便觸發localStorage.setItem 方法,

 實現代碼:

import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)

function storeLocalStore (state) {
  window.localStorage.setItem("userMsg",JSON.stringify(state));
}
const store = new Vuex.Store({
    modules: {
    tags:[],
    curTagsIndex:"-1",
    },
  mutations: {
    SET_CURTAGS: (state, index) => {
      state.curTagsIndex = index
    },
  }
})

export default store

2在 App.vue 的 created 鈎子函數里寫下了如下代碼;

    //在頁面加載時讀取localStorage里的狀態信息
    localStorage.getItem("userMsg") && this.$store.replaceState(Object.assign(this.$store.state,JSON.parse(localStorage.getItem("userMsg"))));
    
    //在頁面刷新時將vuex里的信息保存到localStorage里
    window.addEventListener("beforeunload",()=>{
        localStorage.setItem("userMsg",JSON.stringify(this.$store.state))
    })

原文鏈接:https://blog.csdn.net/aliven1/article/details/80743470

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM