vuex中actions的使用
- 先创建actions和方法
store.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const state = {
count: 1
}
const mutations={
add(state,n){
state.count+=n
},
reduce(state,n){
state.count-=n
}
}
const actions={
addAction(context){
context.commit('add',10)
context.commit('reduce',1)
},
reduceAction({commit}){
commit('reduce',10)
}
}
export default new Vuex.Store({
state,mutations,actions
})
- 使用actions中的方法
count.vue
<template>
<div>
<h3>{{$store.state.count}}========{{count}}</h3>
<hr/>
<p>
<button @click="addAction">+</button>
<button @click="reduceAction">-</button>
</p>
</div>
</template>
<script>
import store from '@/vuex/store'
import {mapState,mapActions} from 'vuex'
export default {
data(){
return{
msg:"hello vuex"
}
},
methods:{
//数组中的名称要和actions中的一致
...mapActions(['addAction','reduceAction'])
},
computed:{
...mapState(['count'])
},
store
}
</script>
<style>
</style>
|你知道的越多,不知道的越多。 |如果本文章内容有问题,请直接评论或者私信我。如果觉得写的还不错的话,点个赞也是对我的支持哦。 |未经允许,不得转载!|微信搜【程序员徐小白】,关注即可第一时间阅读最新文章。回复【面试题】有我准备的50道高频校招面试题,以及各种学习资料。

浙公网安备 33010602011771号