拆分store:
1、创建index.js文件,引入各个模块
import Vue from 'vue'
import Vuex from 'vuex'
import getters from './getters'
import muns from './modules/muns'
import app from './modules/app'
import settings from './modules/settings'
import user from './modules/user'
Vue.use(Vuex)
const store = new Vuex.Store({
modules: {
app,
settings,
user,
muns
},
getters
})
export default store
2、创建store/modules文件夹,分模块创建js文件
例如:
store/modules/user.js文件
import { setToken, getToken } from '@/utils/auth'
import { login, getProfile } from '@/api/user'
import { resetRouter } from '@/router/index'
const state = {
userInfo: {},
token: getToken() || null
}
const mutations = {
setToken: function(state, newToken) {
// 保存到vuex
state.token = newToken
// 保存到cookie
setToken(newToken)
},
setUserInfo(state, newInfo) {
state.userInfo = newInfo
}
}
const actions = {
logout(context) {
// 做退出的操作
// 清空 token, 个人信息
context.commit('setToken', '')
context.commit('setUserInfo', {})
resetRouter()
},
async getProfile(context) {
// 假设拿到数据
const result = await getProfile()
console.log('getProfile......', result)
// 调用mutation
context.commit('setUserInfo', result.data)
// 返回数据 在路由里面使用
return result.data
},
// 登录
async login(context, payload) {
const result = await login(payload)
const token = result.data
// 在action中调用mutation
context.commit('setToken', token)
}
}
export default {
namespaced: true,
state,
mutations,
actions
}
全局getters:
和store/modules统计创建geeters.js文件
const getters = {
sidebar: state => state.app.sidebar,
device: state => state.app.device,
token: state => state.user.token,
// 头像
avatar: state => state.user.userInfo.staffPhoto,
// 名字
name: state => state.user.userInfo.username, // {}.username
departmentName: state => state.user.userInfo.departmentName,
company: state => state.user.userInfo.company,
userId: state => state.user.userInfo.userId
}
export default getters
在main.js文件中引入 :
import store from './store'
new Vue({
// #app 是哪个文件中的dom?
// 1. App.vue
// 2. public/index.html (正确)
el: '#app',
router,
store,
// render: h => h(App)
render: function(h) {
return h(App)
}
})