Vuex的高级使用及localStorage

 index.js文件

import Vue from 'vue'
import Vuex from 'vuex'
import state from './state'
import mutations from './mutations'

Vue.use(Vuex)



export default new Vuex.Store({
    // state: state,键值一样,可以省略值简写为 state
    state,
    actions: {
        changeCity(ctx, city) {
            ctx.commit('changeCity', city)
        }
    },
    mutations
})

 sate.js文件

let defaultCity = '深圳'
try {
    if (localStorage.city) {
        defaultCity = localStorage.city;
    }
} catch (e) {}

export default {

    //如果没有localStorage.city则取默认 '深圳'
    city: defaultCity

}

mutations.js文件

export default {
    changeCity(state, city) {
        state.city = city;
        try {
            localStorage.city = city;
        } catch (e) {};

    }
}

 

目录结构示意图:

Vuex的高级使用及localStorage_第1张图片

你可能感兴趣的:(web前端-Vue)