vuex中actions的使用

  1. 先創建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
})
  1. 使用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>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章