问题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