一、main.js中引入 store
import store from './store'
window.HMO_APP = new Vue({
router,
store,
render: h => h(App)
}).$mount('#app-box')
二、新建store文件夹
index.js为入口js文件
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 三、新建user.js文件夹,用户保存信息
user.js文件
import $ajax from '../../utils/fetch'
const user = {
state: {
info: '', // 用于保存用户信息 }, mutations: {
SET_USER_INFO: (state, info) => {
state.info = info
}, }, actions: {
setUserInfo ({commit}, info) {
commit('SET_USER_INFO', info)
},
loginBySession ({commit, state, dispatch}) {
return new Promise((resolve, reject) => {
$ajax.get('/denglujiekou', data => {
dispatch('setUserInfo', data)
resolve(data)
}, err => {
reject(err)
})
})
}, }
} export default user
四、新建getter.js文件夹,用户获取状态管理里面的信息
const getters = {
userInfo: state => state.user.info, }
export default getters
五、js中使用store方法
import store from '../store/index'
store.getters.idInfo