【问题标题】:Vuex helper methods for mutations用于突变的 Vuex 辅助方法
【发布时间】:2018-06-21 12:17:20
【问题描述】:

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

 mutations: {
     someMethod(){
        this.someReusableCode();
     },
     anotherMethod(){
        this.someReusableCode();
     },
     someReusableCode(){
       ...
     }
 }

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

【问题讨论】:

    标签: javascript vue.js vuejs2 vuex


    【解决方案1】:

    您可以在 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--;
    

    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')
        }
      }
    })
    <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>

    【讨论】:

    • 谢谢,我喜欢你的解决方案,但是在我们的例子中,我们使用的是文件结构,因此我们使用 export default {} 在其自己的 store.js 文件中定义 Vuex 参数对象,然后在我们正在做的 main-vue.js 文件import store_object from store.js' and then let store = new Vuex.Store(store_object);. I would prefer to keep the helper methods in store.js`。我确实发现在 store.js 中的对象之外添加辅助方法是可行的,但不确定这是否是最好的主意。对此策略的任何反馈将不胜感激。
    【解决方案2】:

    您可以将辅助方法保留在 store.js 中。 只需这样做:

    export default new Vuex.Store({
      state: {
        count: 0
      },
      helperMethods: {
        inc: (input, increment) => input + increment
      mutations: {
        incrementByFive(state) { state.count = this.helperMethods.inc(state.count,5) },
      }
    })
    

    【讨论】:

    • 对我不起作用。 this.helperMethods 未定义
    • 我确实设法让它与 const helperMethods 一起使用 - 并使用 helperMethods.inc(没有 this
    猜你喜欢
    • 2020-10-01
    • 2019-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多