浏览器刷新后恢复设置和状态

一种常见的需求是,当处于某种状态(如登录状态),或进行了设置(如地区选择),在浏览器刷新后如何恢复设置和状态。

localStorage保存设置

我一般用localStorage保存重要的设置,而不用来保存状态。因为状态特别关键需要服务器确认。用一点流量还是值得的。
localStorage的setter和getter都应当放到store中处理,然后根据此设置是全局设置还是局部设置,在相应的.vue文件mounted方法中dispatch。如下,注意actions-init和actions-initForLogin

store/area.js

import { getAreaName, setArea } from "@/api/api.js"
import { getLocalStorageArray, getLocalStorageObject, setLocalStorageItem } from '@/tool/localStorage.js'
export default {
  namespaced: true,
  state: function () {
    return {
      cascaderOptions: [],
      currentArea: [/*shengValue,shiValue,xianValue,zhenValue */],
      zhenName: "",/* value: name*/
    }
  },
  mutations: {
    setCurrentArea: function (state, payload) {
      state.currentArea = payload.currentArea
      const JSONCurrentArea = JSON.stringify(payload.currentArea)
      setLocalStorageItem('areaCurrentArea', JSONCurrentArea)
    },
    setName: function (state, payload) {
      state.zhenName = payload.name
    },
    getLSOptions: function (state) {
      state.options = JSON.parse(getLocalStorageObject('areaOptions'))
    },
    getLSCurrentArea: function (state) {
      state.currentArea = JSON.parse(getLocalStorageArray('areaCurrentArea'))
    },
  },
  actions: {
    setName: async function ({ state, commit }) {
      if (state.currentArea && state.currentArea[3]) {
        const obj = await getAreaName(state.currentArea[3])
        commit('setName', { name: obj.name })
      }
    },
    init: async function ({ commit }) {
      commit('getLSOptions')
      commit('getLSCurrentArea')
    },
    initForLogin: async function ({ commit, dispatch, state }) {
      commit('getLSOptions')
      commit('getLSCurrentArea')
      await setArea(state.currentArea[3]);
      dispatch('setName')
      dispatch('getNews', null, { root: true })
      dispatch('getInfos', null, { root: true })
    }
  }
}

然后在需要的此获取该缓存的地方dispatch,下面都是局部.vue调用,后面会给出全局条用的例子

login.vue

  mounted: function() {
    this.__init();
    window.onresize = this.resize;
  },
  destroyed() {
    window.onresize = null;
  },
  methods: {
    __init: async function() {
      this.$store.dispatch("area/initForLogin");
      this.resize();
      this.getVerifyPictureSrc();
    },
    resize: debounce(function() {
      this.height = scaleHeightWithWindow(0.75);
    }, 100),
    getVerifyPictureSrc: async function() {
      await deleteVerifyPicture();
      this.verifyPictureSrc = "/api/verifypic?force=" + Math.random();
    },
    userLogin: function() {
      this.$store.dispatch("user/login", {
        callback: this.getVerifyPictureSrc
      });
      // this.getVerifyPictureSrc();
    },
    logout: function() {
      this.$store.dispatch("user/logout", { router: this.$router });
    }
  },

poster.vue

mounted() {
    this.___init();
    this.handlerResize();
    window.onresize = debounce(this.handlerResize, 300);
    this.throttleHandleScroll = throttle(this.handleScroll, 600);
    window.addEventListener("mousewheel", this.throttleHandleScroll);
    window.addEventListener("DOMMouseScroll", this.throttleHandleScroll);
  },
  destroyed() {
    window.onresize = null;
    window.removeEventListener("mousewheel", this.throttleHandleScroll);
    window.removeEventListener("DOMMouseScroll", this.throttleHandleScroll);
  },
  methods: {
    handleScroll: function(e) {
      if ((e.detail || e.deltaY) > 0) this.$refs.carousel.next();
      else this.$refs.carousel.prev();
    },
    handlerResize: function() {
      this.height = window.innerHeight + "px";
    },
    ___init: async function() {
      await this.$store.dispatch("area/init");
    }
  }

从后台请求状态

注意actions-init

store/user.js

/**
 * 用户登录
 */
import { userLogin, getLoginInfo, logout } from '@/api/api.js'
import Vue from 'vue'
export default {
  namespaced: true,
  state: function () {
    return {
      loginInfo: {
        name: '',
        pass: '',
        verify: '',
        type: 1, /*1是政府账户 2是企业账户 */
      },
      loginStatus: -4/**0-成功 -1 -2 -3 -4 */
    }
  },
  mutations:
  {
    setName: function ({ loginInfo }, { name }) {
      loginInfo.name = name
    },
    setPass: function ({ loginInfo }, { pass }) {
      loginInfo.name = pass
    },
    setVerify: function ({ loginInfo }, { verify }) {
      loginInfo.verify = verify
    },
    setType: function ({ loginInfo }, { type }) {
      loginInfo.verify = type
    },
    setStatus: function (state, { status }) {
      state.loginStatus = status
    },
    reset: function (state) {
      state.loginStatus = -4;
      const { loginInfo } = state;
      loginInfo.name = '';
      loginInfo.pass = '';
      loginInfo.verify = '';
    }
  },
  actions: {
    login: async function ({ state, commit }, { callback }) {
      const res = await userLogin(state.loginInfo)
      const v = res.code
      commit('setStatus', { status: v })
      if (v == 0) {
        Vue.prototype.$message({
          type: "success",
          message: "登录成功"
        });
      } else {
        let msg =
          v == -1 ? "验证码错误" : v == -2 ? "用户名或密码错误" : "用户不存在";
        Vue.prototype.$message({
          type: "error",
          message: msg
        });
      }
      callback()
    },
    logout: async function ({ commit }, { router }) {
      await logout()
      commit('reset')
      router.push('login')
    },
    init: async function ({ commit }) {
      const loginInfo = await getLoginInfo()
      const { loginName, loginType/**cityId,provinceId */ } = loginInfo
      commit('setName', { name: loginName })
      commit('setStatus', { status: (loginType == 1 ? 0 : -1) })
    }
  }
}

这个状态属于全局状态,每次刷新站都要请求

app.vue

  mounted() {
    this.$store.dispatch("user/init");
  }

谢谢

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容