Bryan Miller
Bryan Miller

Reputation: 3323

Vuex helper methods for mutations

In Vuex, I have my mutations object as follows:

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

However, I'm getting an error that someReusableCode() isn't defined. Where is the best place to define my someReusableCode() method so this will work?

Upvotes: 7

Views: 9466

Answers (3)

Bryce Rakop
Bryce Rakop

Reputation: 184

@siem simonis has the right answer, though with Vue3 I did it this way:

const helperMethods = {
componentToHex(c) {
    var hex = c.toString(16);
    return hex.length == 1 ? "0" + hex : hex;
  },
  rgbToHex(r, g, b) {
    return "#" + this.componentToHex(r) + this.componentToHex(g) + this.componentToHex(b);
  },
  hexToRgb(hex) {
    var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
    return result ? {
      r: parseInt(result[1], 16),
      g: parseInt(result[2], 16),
      b: parseInt(result[3], 16)
    } : null;
  },};

Then to call the helper:

RGB=helperMethods.hexToRgb(state.Theme[ThemeKeys[x]])

And you do not need to add it to you export at the end of your store, just FYI.

Upvotes: 1

siem simonis
siem simonis

Reputation: 21

You can keep the helper methods inside store.js. Just do this:

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

Upvotes: 1

tony19
tony19

Reputation: 138206

You could define a shared method off the store object (instance of 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/[email protected]/dist/vue.js"></script>
<script src="https://unpkg.com/[email protected]/dist/vuex.js"></script>

<div id="app">
  <p>{{ count }}</p>
  <p>
    <button @click="increment">+</button>
    <button @click="decrement">-</button>
  </p>
</div>

Upvotes: 3

Related Questions