vue中localStorage的使用
在原有的项目中,需要缓存效果。h5中新增了localstorage,可以用于缓存。代码修改如下:
store/index.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 {
if (localStorage.city) {
defaultCity = localStorage.city;
}
} catch (e) {
}
}
}
})
注意:在使用localstorage的时候,建议大家使用try/catch。因为在某些浏览器中,如果用户关闭了本地存储或者使用隐身模式,使用localstorage,浏览器会抛出异常。
但是,此时index.js文件变得复杂了,我们可以进行拆分,便于管理与维护。
拆分步骤:
(1)在store下新建state.js文件,将store/index.js中对应的内容剪切到state.js文件中。
let defaultCity = '北京';
try {
if (localStorage.city) {
defaultCity = localStorage.city;
}
} catch (e) {
}
export default {
city: defaultCity
}
(2)分析上面代码,该文件已经导出。我们在index.js中引用即可。
import state from './state.js'
export default new Vuex.Store({
state, // 引入
mutations: {
changeCity(state, city){
state.city = city;
try {
if (localStorage.city) {
defaultCity = localStorage.city;
}
} catch (e) {
}
}
}
})
同理,我们拆分mutations,然后引入到index.js中。
mutations.js文件
/**
* Created by yangbaoshuai on 2018/8/16.
*/
export default {
changeCity(state, city){
state.city = city;
try {
localStorage.city = city;
} catch (e) {
}
}
}
当选取的城市文字较多的时候,出现拥挤换行的情况。究其原因,是我们把对应的文字所在的标签宽度固定了,我们做如下修改:将width修改为min-width,并设置padding。
.header-right
min-width 1.04rem
pading 0 0.1rem