vuex 中,正规改共享数据流程是 组件-> Action -> Mutations -> State ,如果不是批量改state的数据的时候,其实可以省略Action (dispatch) (commit)
mapState 是映射state对象的数据,简化代码结构
index.js
export default new Vuex.Store({ state, /*actions:{ changeCity(ctx,city){ ctx.commit('changeCity',city) } },*/ mutations })
state.js:
let defaultCity = '上海' try { if(localStorage.city){ defaultCity = localStorage.city } }catch(e) {} export default { city:defaultCity }
xx.vue:
import {mapState} from 'vuex'
computed:{ ...mapState(['city']) },
mapMutations 是映射方法,前面基本一样
...mapMutations(['changeCity'])
this.changeCity(city)mapGetters相当于computed,根据state的数据二次计算出新数据