zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    10 vue中 v-model ,计算机demo
    linear-gradient
    flexible.js
    九宫格抽奖原理
    js匿名函数与闭包作用
    HTML5实现九宫格布局
    scrollLeft/scrollTop/scrollHeight
    通过media媒体查询设置ie7/8样式、使用media判断各机型、手淘flexible.js
    右击事件oncontentmenu
    js/jquery判断一个对象是否为空
  • 原文地址:https://www.cnblogs.com/xieli26/p/9947391.html
Copyright © 2011-2022 走看看