soter 结构
//soter 结构 ─store │ getters.js │ index.js │ └─modules user.js
modules
/store/modules/user.js /** * 用户信息 * */ const user = { state: { userInfo:{},//用户信息 }, mutations: { SET_USER_INFO(state, userInfo) { state.userInfo = userInfo }, }, actions: { SetUserInfo({commit}, userInfo) { commit('SET_USER_INFO', userInfo) }, } } export default user
getters
/store/getters.js /** * 全局数据响应写在这 * */ const getters = { userInfo: state => state.user.userInfo } export default getters
store 入口文件
/store/index.js /** * store 总线 * */ import Vue from 'vue' import Vuex from 'vuex' import user from './modules/user' import getters from './getters' Vue.use(Vuex) const store = new Vuex.Store({ modules: { user, }, getters, }) export default store
把store挂载到vue对象上
//引入使用 import store from './store'; store.dispatch('SetUserInfo',{name:'张三'}) //调用 new Vue({ router, store, components:{App}, template:'<App/>' }).$mount('#app')
取值
{{$store.getters.userInfo}} //响应模式 {{$store.state.user.userInfo}} //直接取值