目录结构
分割模块 modules
每个模块拥有自己的 state、mutation、action、getter、甚至是嵌套子模块
// user.js
import { login, logout, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'
const state = {
token: getToken(),
name: '',
avatar: ''
}
const mutations = {
SET_TOKEN: (state, token) => {
state.token = token
},
SET_NAME: (state, name) => {
state.name = name
},
SET_AVATAR: (state, avatar) => {
state.avatar = avatar
}
}
const actions = {
// user login
login({ commit }, userInfo) {
},
// get user info
getInfo({ commit, state }) {
},
// user logout
logout({ commit, state }) {
commit('SET_TOKEN', '值')
},
// remove token
resetToken({ commit }) {
return new Promise(resolve => {
commit('SET_TOKEN', '')
removeToken()
resolve()
})
}
}
export default {
namespaced: true, // 成为带命名空间的模块
state,
mutations,
actions
}
其他模块根据项目需要创建对应模块的js
文件
getters.js
const getters = {
// 变量名: state => state.文件名.变量名
token: state => state.user.token,
avatar: state => state.user.avatar,
name: state => state.user.name
}
export default getters
index.js
- 手动逐个引入modules(没添加一个模块文件,就要到这里来引入)
import Vue from 'vue'
import Vuex from 'vuex'
import getters from './getters'
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
},
getters
})
export default store
- 代码引入modules(后续添加的js模块不需要额外的手动引入)
这里是在vue-element-admin-4.2.1
的开源项目代码中看到的
import Vue from 'vue'
import Vuex from 'vuex'
import getters from './getters'
Vue.use(Vuex)
// https://webpack.js.org/guides/dependency-management/#requirecontext
const modulesFiles = require.context('./modules', true, /\.js$/)
console.log('modulesFiles',modulesFiles);
// you do not need `import app from './modules/app'`
// it will auto require all vuex module from modules file
const modules = modulesFiles.keys().reduce((modules, modulePath) => {
// set './app.js' => 'app'
const moduleName = modulePath.replace(/^\.\/(.*)\.\w+$/, '$1')
const value = modulesFiles(modulePath)
modules[moduleName] = value.default
return modules
}, {})
const store = new Vuex.Store({
modules,
getters
})
export default store
main.js
import store from './store'
new Vue({
el: '#app',
router,
store,
render: h => h(App)
})
组件中使用
vuex里面 mapState
、mapGetters
、mapMutations
、mapActions
等方法都可使用,这里就记录一写简单使用已经足够了。
1. 获取参数
// 1:
import { mapGetters } from 'vuex'
computed: {
...mapGetters([
'sidebar',
'avatar'
])
},
// 2:
computed: {
avatar() {
return this.$store.state.user.avatar
}
},
2. 触发actions
// this.$store.dispatch('模块名称/actions里面的方法')
this.$store.dispatch('user/resetToken')
// store.dispatch 可以处理被触发的 action 的处理函数返回的 Promise,并且 store.dispatch 仍旧返回 Promise
this.$store.dispatch('user/resetToken').then(()=>{ ... })