- 先創建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:{
...mapActions(['addAction','reduceAction'])
},
computed:{
...mapState(['count'])
},
store
}
</script>
<style>
</style>