1.vuex中的辅助函数
这里面就是个简单的使用哈,大道至简殊途同归
mapState,mapGetters,mapMutations,mapActions,
- 不改名属性名:
...map+“名字”(["属性名字1","属性名字2"]) - 改属性名字:
...map+“名字”({"新属性名字":vuex中的属性名字})
<template>
<div class="about">
<h1>This is an about page</h1>
<p>{{name}}</p>
<p>{{count}}</p>
<p>{{evenOrOdd}}</p>
<div>
<button @click="add">+ 1</button>
</div>
<div>
<button @click="decrease">-1</button>
</div>
</div>
</template>
<script>
import {
mapGetters,
// mapActions,
mapMutations,
mapActions
} from 'vuex';
export default {
//不改名字的写法
// computed: {
// ...mapState(['count', 'name']),
// },
//这个是改名的写法
// computed: {
// ...mapState({
// mylove: "name",
// mycount: "count"
// })
// },
computed: {
//这个是getters中的
// evenOrOdd() {
// return this.$store.getters.evenOrOdd;
// },
...mapGetters(["evenOrOdd"])
},
methods: {
//
...mapMutations(["add", "decrease"]),
//这个是异步的
// ...mapActions([""])
// add() {
// this.$store.commit('add');
// },
// decrease() {
// this.$store.commit('decrease');
// },
},
};
</script>
2.提交方式:
this.$store.dispatch和this.$store.commit除了基本的负荷方式外,还可以传入对象--->{type:"触发的函数名",参数key:参数value}
<template>
<div class="about">
<h1>This is an about page</h1>
<!-- <p>{{name}}</p> -->
<p>{{count}}</p>
<p>{{evenOrOdd}}</p>
<div>
<button @click="add">+ 1</button>
</div>
<div>
<button @click="decrease">-1</button>
</div>
</div>
</template>
<script>
import {
mapGetters,
mapState,
} from 'vuex';
export default {
computed: {
...mapState(["count"]),
...mapGetters(["evenOrOdd"])
},
methods: {
add() {
this.$store.dispatch({
type: "goAdd",
amount: 10
})
},
decrease() {
this.$store.commit({
type: "decrease",
dmount: 5
})
}
},
};
</script>
🌵store的index.js中的函数,可以通过解构拿到对应的参数做处理:
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
count:0,
name:"linlin"
},
getters:{
evenOrOdd(state){
return state.count % 2 == 0 ? "偶数":"奇数"
}
},
mutations: {
add(state,data){
state.count = state.count + data;
},
decrease(state,{dmount}){
state.count = state.count - dmount ;
}
},
actions: {
goAdd({commit},{amount}){
console.log(amount);
commit("add",amount)
}
},
modules: {
}
})