用于突变的 Vuex 辅助方法

use*_*840 6 javascript vue.js vuex vuejs2

在 Vuex 中,我的突变对象如下:

 mutations: {
     someMethod(){
        this.someReusableCode();
     },
     anotherMethod(){
        this.someReusableCode();
     },
     someReusableCode(){
       ...
     }
 }
Run Code Online (Sandbox Code Playgroud)

但是,我收到一个someReusableCode()未定义的错误。定义我的someReusableCode()方法的最佳位置在哪里?

ton*_*y19 3

store您可以定义对象( 的实例)的共享方法Vuex.Store

const store = new Vuex.Store({
  state: {
    count: 0
  },
  mutations: {
    increment(state) { this.inc(state) },
    decrement(state) { this.dec(state) }
  }
})

// Shared functions of store
store.inc = state => state.count++;
store.dec = state => state.count--;
Run Code Online (Sandbox Code Playgroud)

const store = new Vuex.Store({
  state: {
    count: 0
  },
  mutations: {
    increment(state) { this.inc(state) },
    decrement(state) { this.dec(state) }
  }
})

// Shared functions: inc() and dec()
store.inc = state => state.count++
store.dec = state => state.count--

new Vue({
  el: '#app',
  computed: {
    count() {
      return store.state.count
    }
  },
  methods: {
    increment () {
      store.commit('increment')
    },
    decrement () {
      store.commit('decrement')
    }
  }
})
Run Code Online (Sandbox Code Playgroud)
<script src="https://unpkg.com/vue@2.5.13/dist/vue.js"></script>
<script src="https://unpkg.com/vuex@3.0.1/dist/vuex.js"></script>

<div id="app">
  <p>{{ count }}</p>
  <p>
    <button @click="increment">+</button>
    <button @click="decrement">-</button>
  </p>
</div>
Run Code Online (Sandbox Code Playgroud)