// store
import { createStore } from 'vuex'
export default createStore({
state: {
count: 0
},
mutations: {
sub(state) {
state.count--;
}
},
actions: {
},
modules: {
}
})
// 通过mapMutations函数将store中的sub函数映射为自己的函数,就可以直接使用了
<template>
<div>
<button @click="btnHandler1">-1</button>
</div>
</template>
<script>
import { mapMutations } from "vuex";
export default {
methods: {
...mapMutations(['sub']),
btnHandler1() {
this.sub();
}
}
};
</script>
// store
export default createStore({
state: {
count: 0
},
mutations: {
sub(state) {
state.count--;
}
},
actions: {
subAsync(context){
setTimeout(function(){
context.commit('sub')
}, 2000);
}
}
})
// 子组件Subtraction.vue
<script>
import { mapActions } from "vuex";
export default {
methods: {
...mapActions(['subAsync'])
<!-- ,btnHandler3() {
this.subAsync();
} -->
}
};
</script>
<!-- 不需要在methods中调用subAsync方法,直接使用即可 -->
<template>
<div>
<button @click="subAsync()">-1_Async</button>
</div>
</template>
- actions异步调用mutations中的函数,同时传参,方式2
// store
export default createStore({
state: {
count: 0
},
mutations: {
subN(state, step) {
state.count -= step;
}
},
actions: {
subNAsync(context, step){
setTimeout(function(){
context.commit('subN', step)
}, 2000)
}
}
})
// 引入store中的subNAsync函数
<script>
import { mapActions } from "vuex";
export default {
methods: {
...mapActions(['subNAsync'])
}
};
</script>
// 直接使用
<template>
<div>
<button @click="subNAsync(2)">-N_Async</button>
</div>
</template>