首页 > 其他 > 详细

localStorage的使用问题

时间:2019-10-14 09:52:54      阅读:65      评论:0      收藏:0      [点我收藏+]

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

方法:使用try-catch包裹

代码示例:

store.js
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) } } })

问题2:当vuex的store.js变得复杂起来时,代码看着会很庞大

方法:将state、mutations、actions拆分出去

代码示例:

创建state.js
let defaultCity = ‘汉中‘
try {
  if (localStorage.city) {
    defaultCity = localStorage.city
  }
} catch (e) {}

export default {
  city: defaultCity 
}
store.js
import Vue from ‘vue‘ import Vuex from ‘vuex‘ import state from ‘./state‘ Vue.use(Vuex) export default new Vuex.Store({ state: state, //键名键值相同,还可以简化 mutations: { changeCity (state, city) { state.city = city try { localStorage.city = city } catch (e) {} } }, actions: { changeCity (ctx, city) { // ctx为上下文,city是传来的参数 ctx.commit(‘changeCity‘, city) } } })

同样可以创建mutations.js、actions.js

localStorage的使用问题

原文:https://www.cnblogs.com/VCplus/p/11669655.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!