Vuex安装
npm n install vuex --save
Vuex使用案列
- store/index.js
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$/)
// 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
}, {})
export default new Vuex.Store({
modules,
getters
})
- store/getters.js
const getters = {
username:state => state.user.username,
}
export default getters
- store/modules/user.js
const types = {
SET_USERNAME: 'SET_USERNAME', // 用户名称
}
const state = {
username: ''
}
const mutations = {
[types.SET_USERNAME](state, username) {
state.username = username;
},
};
const actions = {
/**登录 */
login({ commit, state },userInfo){
return new Promise((resolve, reject) => {
// login(state.userInfo).then(res=>{
// resolve();
// }).catch(err=>{
// reject(err)
// })
})
}
}
export default {
//namespaced这是属性用于解决不同模块的命名冲突问题,在不同页面引入getter、actions、mutations时,要加上模块名
namespaced: true,
state,
mutations,
actions
}
注意:最后在main.js中引入
在模块中使用mapState,mapGetters,mapMutations,mapActions
import { mapState, mapGetters, mapActions } from "vuex"
...
computed: {
...mapState({
username: state => state.user.username
}),
...mapGetters(["username"])
},
...
methods:{
...mapActions('user',['login']),
//或者用以下方法使用子模块中的Action
// ...mapActions({
// loginOut: "user/loginOut"
// }),
}
...