• 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这是我剥离出来的部分。

  • 相关阅读:
    使用 Visual Studio 2022 开发 Linux C++ 应用程序
    CSDN博客 新版主页与旧版主页切换
    C++ 静态局部变量 全局变量
    静态构造函数
    使用jquery的ajax功能post数据
    图片的禁止缓存与预缓存
    cookie
    asp.net中使用excel类导出Excel文件,并导出到web客户端中遇到的问题
    xmlHttpRequest对象的使用
    html静态文件提交到aspx页面处理
  • 原文地址:https://www.cnblogs.com/yihuite-zch/p/10648830.html
Copyright © 2020-2023  润新知