本文通过模块化使用方法来介绍
在srore文件创建vuexuse文件夹,并在该文件夹下创建index.js文件
在index文件写需要的数据
export default {
namespaced: true,
state: {
num: 100,
numtwo:200
},
getters: {
doubleCount(state) {
return state.num * 2;
},
doubleCounttwo(state) {
return state.numtwo * 3;
}
},
mutations: {
getmmutsttos(state, apply) {
state.num += apply
},
getmmutsttostwo(state, apply) {
state.numtwo += apply
}
},
actions: {
setactionsend(context, apply) {
context.commit('getmmutsttos', apply)
},
setactionsendtwo(context, apply) {
context.commit('getmmutsttostwo', apply)
}
}
}
在store文件夹下的index.js注册vuexuse模块
import Vue from 'vue'
import Vuex from 'vuex'
import vuexuse from './vuexuse'
Vue.use(Vuex)
export default new Vuex.Store({
modules: {
vuexuse
}
})
然后按照下面方式使用即可
<template>
<div class="container">
<div class="one">
<h3>第一种原始的使用方法</h3>
<div>state的值:{{ $store.state.vuexuse.num }}</div>
<div>getter的double值:{{ thisDoubleCount }}</div>
<div><button @click="update">mutations修改state的值+10</button></div>
<div><button @click="ybupdate">异步actions的值+100</button></div>
</div>
<div class="one two">
<h3>第二种map方式的使用方法</h3>
<div>state的值:{{ numtwo }}</div>
<div>getter的3倍值:{{ doubleCounttwo }}</div>
<div><button @click="updatetwo">mutations修改state的值+20</button></div>
<div><button @click="ybupdatetwo">异步actions的值+200</button></div>
</div>
</div>
</template>
<script>
import { mapState, mapGetters, mapMutations, mapActions } from "vuex";
export default {
data() {
return {};
},
created() {
document.title = "vuex的两种使用方法使用";
},
methods: {
...mapMutations("vuexuse", ["getmmutsttostwo"]),
...mapActions("vuexuse", ["setactionsendtwo"]),
update() {
this.$store.commit("vuexuse/getmmutsttos", 10);
},
ybupdate() {
this.$store.dispatch("vuexuse/setactionsend", 100);
},
updatetwo() {
this.getmmutsttostwo(20);
},
ybupdatetwo() {
this.setactionsendtwo(200);
},
},
computed: {
...mapState("vuexuse", ["numtwo"]),
...mapGetters("vuexuse", ["doubleCounttwo"]),
thisDoubleCount() {
return this.$store.getters["vuexuse/doubleCount"];
},
},
components: {},
};
</script>
<style scoped lang='less'>
.container {
.one {
padding: 10px;
border: 1px solid #ddd;
border-radius: 10px;
}
.two {
margin-top: 20px;
}
button {
margin: 10px;
}
}
</style>