localStorage的使用问题

六眼飞鱼酱① 提交于 2019-12-01 07:43:43

问题:在隐身模式、或者用户未启用的情况下,使用localStorage可能会导致浏览器直接报错,怎么办?

方法:使用try-catch包裹

代码示例:

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

let defaultCity = '汉中'
try {
  if (localStorage.city) {
    defaultCity = localStorage.city
  }
} catch (e) {}

export default new Vuex.Store({
  state: {
    city: defaultCity
  },
  mutations: {
    changeCity (state, city) {
      state.city = city
      try {
        localStorage.city = city
      } catch (e) {}
    }
  },
  actions: {
    changeCity (ctx, city) {
      // ctx为上下文,city是传来的参数
      ctx.commit('changeCity', city)
    }
  }
})

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!