/store/index.js
import Vue from 'vue'
import Vuex from 'vuex'
import user from './modules/user'
Vue.use(Vuex)
export default new Vuex.Store({
modules: {
user
}
})
/store/modules/user.js
const user = {
namespaced: true, //命名空间
state: {
userName: 'admin',
},
mutations: {
SET_USERNAME: (state, userName) => {
state.userName = userName
}
},
actions: {
AsyncChangeUserName({ commit }, userName) {
commit('SET_USERNAME', userName)
}
}
}
export default user
index.vue
<template>
<div class="index">
<h2>全局参数userName的值:{{ userName }}</h2>
<button @click="changeName">改变userName的值</button>
</div>
</template>
<script>
import { mapState, mapMutations, mapActions } from "vuex"
export default {
name: "IndexView",
computed: {
...mapState("user", ["userName"]),
},
methods: {
...mapMutations("user", ["SET_USERNAME"]),
...mapActions("user", ["AsyncChangeUserName"]),
changeName() {
// 异步action
this.AsyncChangeUserName("zhangsan")
// this.$store.dispatch("user/AsyncChangeUserName", "zhangsan")
// 同步mutation
// this.SET_USERNAME("zhangsan")
// this.$store.commit("user/SET_USERNAME", "zhangsan")
}
},
watch: {
userName(newValue, oldValue) {
console.log(newValue, oldValue)
},
},
}
</script>