state:存储数据
mutations:修改数据,不能执行异步操作
action:操作mutations,可以任意执行异步操作
getters:操作state中的数据,并在getters方法中单独缓存,响应式,类似计算属性computed
modules:把store中的数据和方法分成模块
读取store数据
```html
state
state:{{ $store.state.cityModule.cityName }}
辅助函数mapState:{{ cityName }}
<h4>getters</h4>
<p>getters:{{ $store.getters['cityModule/cityVal'] }}</p>
<p>辅助函数:{{ cityVal }}</p>
import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex)
const store = new Vuex.Store({ //5. 模块 用户信息 城市数据 购车数据 搜索数据 ... modules:{ //5.1 城市数据 cityModule:{ namespaced:true,//开启命名空间 让actions mutations getters的作用域是当前的模块下 state:{ cityName:'北京' }, getters:{ cityVal:state=>{ return state.cityName +'帝都' } }, mutations:{ changeCity(state,payload){ state.cityName = payload } }, actions:{ getCity(context,city){ context.commit('changeCity',city) } } } } }) //导出 export default store; ```
局部模块访问全局数据
只有getters和actions有此功能
```js export default { namespaced:true, state:{ cityName:'北京' }, mutations:{ changeCity(state,payload){ state.cityName = payload } }, getters:{ // state和getters访问本模块内的,rootState和rootGetters访问全局的 getGlobalCity(state,getters,rootState,rootGetters){} }, actions:{ //局部context对象可以访问全局state getters mutations actions和其他模块 //context={dispatch:'',commit:'',state:'',getters:'',rootState:'',rootGetters} getGlobalAction(context){ console.log(context);
//可以访问全局到的actions和mutations,加入第三个参数
context.commit('changeUser','全局的user',{root:true});
}
}
} ```