zoukankan      html  css  js  c++  java
  • 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这是我剥离出来的部分。

  • 相关阅读:
    QT中的列表容器
    QT中的Buttons
    QT中的常用控件
    [机房测试]弟娃
    CF1580C Train Maintenance
    [机房测试]数据恢复
    Sentry 监控
    Sentry 监控
    Sentry 监控
    Sentry 后端监控
  • 原文地址:https://www.cnblogs.com/yihuite-zch/p/10648830.html
Copyright © 2011-2022 走看看