index.js
import Vue from "vue";
import Vuex from "vuex";
Vue.use(Vuex);
const store = new Vuex.Store({
modules: {
"user": {
//命名空间
namespaced: true,
state: {
use: "gao"
},
mutations: {
changeUser(state) {
state.use = "王"
}
},
getters: {
x(state) {
return state.use.toUpperCase()
}
},
actions: {
ccc({
commit
}) {
commit("changeUser")
}
}
},
"goods": {
namespaced: true,
state: {
goods: "小米"
},
mutations: {},
getters: {},
actions: {}
},
}
})
export default store;
app.vue
<template>
<div id="app">
{{ $store.state.user.use }}
{{ un1 }}
{{ use }}
{{ un2 }}
<hr />
{{ x }}
<button @click="fn1">切换用户名2</button>
<button @click="changeUser">切换用户名3</button>
<button @click="ccc">切换用户名4</button>
</div>
</template>
<script>
import { mapState, mapGetters, mapMutations, mapActions } from "vuex";
export default {
computed: {
un1() {
return this.$store.state.user.use;
},
...mapState("user", ["use"]),
...mapState("user", { un2: "use" }),
/
...mapGetters("user", ["x"]),
},
methods: {
fn1() {
this.$store.commit("user/changeUser");
},
...mapMutations("user", ["changeUser"]),
/
...mapActions("user", ["ccc"]),
},
};
</script>
<style>
</style>