vuex一般情况下和vue脚手架配合使用,vuex可以共享数据,使用action,mutation进行更新数据,组件中使用commit进行提交调用,在我们使用这些东西的时候,我们也可以使用vuex中的辅助函数在组件中简化获取值的操作。
mapState使用方式
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| //在data.vue中
import { mapState } from 'vuex'
//computed: mapState({
//count: state => state.count //方法一
//count:"count"//方法二
// num (state) { //方法三
// return state.count + 100
// }
//})
//computed: mapState(['count'])
computed: {
abc () {
return 123
},
...mapState(['count'])
} |
mapActions使用方法
1 2 3 4 5 6 7 8 9 10 11 12 13
| //data.vue中
import { mapState, mapGetters, mapActions } from 'vuex'
//data.vue中methods中的写法
//不使用mapActions
handleIncrement () {
this.$store.dispatch('increment');
}
//使用mapActions
...mapActions({
handleIncrement: 'increment' //handleIncrement表示的就是事件执行函数
}) |
mapMutations使用方法
1 2 3 4 5 6 7 8 9 10 11 12 13
| //data.vue中
import { mapState, mapGetters, mapActions,mapMutations } from 'vuex'
//data.vue中methods中的写法
//不使用mapMutations
handleIncrement () {
this.$store.dispatch('decrease');
}
//使用mapMutations
...mapMutations({
handleIncrement: 'decrease' //handleIncrement表示的就是事件执行函数
}) |
使用mapMutations传值要在函数里面去做,示例如下:
不可以在methods中去做
1 2 3 4 5 6 7 8 9 10 11 12
| //data.vue
<button @click="handleIncrement('{de:5}')">减少</button>
...mapMutations({
handleIncrement: 'decrease'
}),
//store.js
decrease(state, data) {
state.count--;
console.log(data);
} |
每当点击一次减,就会在控制台打印出我们调用的值
「梦想一旦被付诸行动,就会变得神圣,如果觉得我的文章对您有用,请帮助本站成长」
共 0 条评论关于"vuex辅助函数mapState、mapActions"
最新评论