vue之常用的辅助函数mapState、mapMutations、mapActions![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/0394628922bd1b1a69e0a4e3153a952a.png#pic_center)
store / modules / about.js
import { ADD_COUNT, SUB_COUNT } from "../mutation-type";
const state = {
msgArr: ["1", "2"],
count: 1,
}
const mutations = {
set_msg (state, payload) {
state.msgArr = payload;
},
[SUB_COUNT] (state, payload) {
state.count = payload;
},
[ADD_COUNT] (state, payload) {
state.count = payload;
}
}
const actions = {
sub_count ({ commit }, payload) {
setTimeout(() => {
commit(SUB_COUNT, payload)
}, 1000);
},
add_count ({ commit }, payload) {
setTimeout(() => {
commit(ADD_COUNT, payload)
}, 1000);
}
}
export default {
namespaced: true,
state,
mutations,
actions
};
store / mutation-type.js
// 关于
export const ABOUT_MSG_ARR = 'about_msgArr'; // about的信息
export const ADD_COUNT = 'add_count'; // count add值
export const SUB_COUNT = 'sub_count'; // count sub值
About.vue
- 对mapMutations 与 mapActions 与 mapState 的使用
<template>
<div>
<div>测试vuex -- msgArr-{{ msgArr }} -- count-{{ count }}</div>
<button @click="subBtn">-</button>
<button @click="addBtn">+</button>
</div>
</template>
<script>
import { mapState, mapMutations, mapActions } from "vuex";
export default {
name: "About2",
components: {},
data() {
return {
};
},
created() {
// 调用 mutations 解构出来的 commit方法 ,并且提交传递数据
this.set_msg([11, 22, 33]);
},
computed: {
...mapState("about", ["msgArr", "count"]),
},
methods: {
...mapMutations("about", ["set_msg"]),
...mapActions("about", ["add_count", "sub_count"]),
// 如果是某一个module下的mutation,需要带上namespace
// ...mapMutations('home', ['setActiveList']), // 🚀 数组形式
// ...mapMutations('home', { setActives: 'setActiveList' }), // 🚀 对象形式
subBtn() {
let count = this.count - 1;
count = count <= 0 ? 0 : count;
// 调用 actions解构出来的 dispatch方法 ,并且提交传递数据
this.sub_count(count);
},
addBtn() {
let count = this.count + 1;
this.add_count(count);
},
},
};
</script>