4

我正在使用以下代码使用 Vuex 在 store.js 中增加一个计数器。不知道为什么,当我点击增量按钮时,它说:

[vuex] 未知动作类型:INCREMENT

store.js

import Vuex from 'vuex'
import Vue from 'vue'
Vue.use(Vuex)
var store = new Vuex.Store({
  state: {
    counter: 0
  },
  mutations: {
    INCREMENT (state) {
      state.counter++;
    }
  }
})
export default store

IcrementButton.vue

<template>
  <button @click.prevent="activate">+1</button>
</template>

<script>
import store from '../store'

export default {
  methods: {
    activate () {
      store.dispatch('INCREMENT');
    }
  }
}
</script>

<style>
</style>
4

1 回答 1

7

您必须commit在触发突变时使用方法,而不是动作

export default {
  methods: {
    activate () {
      store.commit('INCREMENT');
    }
  }
}

动作类似于突变,不同之处在于:

  • 动作不是改变状态,而是提交突变。
  • 动作可以包含任意异步操作。
于 2016-12-21T05:24:14.827 回答