vuex刷新頁面數據重置問題


由於vuex是保存在內存中的所以每次頁面刷新數據都會被重置,相當於重新加載js代碼。

那么看了很多頁面,登入后刷新頁面用戶數據不消失的問題又是怎么做的呢?

小編總結了兩個方案

方法一:利用beforeunload事件在用戶刷新頁面時將vuex的store存入sessionstorage中然后再在頁面加載時獲從sessionstorage中獲取,replaceState  store,然后清除

    sessionstorage。

    代碼如下:

//在app.vue中插入
<template>
  <div id="app">
    <router-view/>
  </div>
</template>

<script>
export default {
  name: 'App',
  created () {
    //在頁面加載時讀取sessionStorage里的狀態信息
    if (sessionStorage.getItem("store") ) {
      this.$store.replaceState(Object.assign({}, this.$store.state,JSON.parse(sessionStorage.getItem("store"))));
      sessionStorage.removeItem('store');
    }

    //在頁面刷新時將vuex里的信息保存到sessionStorage里
    window.addEventListener("beforeunload",()=>{
      sessionStorage.setItem("store",JSON.stringify(this.$store.state))
    })
  }
}
</script>

<style>
#app {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

  

方法二:也是我研究iview-admin時總結出來的方法。登入時保存token在cookie中,store中保存的token用函數指向這個cookie,再路由守衛中做控制當token存在但卻沒有用戶信息時調用獲取用戶信息的actiion方法為store中的用戶信息重新賦值,也就是在每次刷新頁面時都會重新請求一遍用戶信息。github地址:https://github.com/zch0451/template這是我剝離出來的部分。


免責聲明!

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



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