Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 732
Bryan Miller Avatar asked Jan 12 '18 04:01

Bryan Miller


People also ask

How do you call a mutation in Vuex?

In Vuex, mutations are synchronous transactions: store.commit('increment') // any state change that the "increment" mutation may cause // should be done at this moment. To handle asynchronous operations, let's introduce Actions.

How do you access getters in mutations Vuex?

To access getters within Vuex mutations with Vue. js, we just use the state in the getter and call the getter with the state . //... const store = new Vuex.

Can I call action from mutation Vuex?

In Vuex, actions are functions that call mutations. Actions exist because mutations must be synchronous, whereas actions can be asynchronous. You can define actions by passing a POJO as the actions property to the Vuex store constructor as shown below. To "call" an action, you should use the Store#dispatch() function.

How would you commit a mutation from another module Vuex?

To change another module state from one module in Vuex, we can call commit with the mutation name with the root option set to true . commit("TOGGLE_LOADING", null, { root: true }); to call commit to commit the TOGGLE_LOADING mutation with root set to true .


1 Answers

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>
like image 52
tony19 Avatar answered Nov 15 '22 00:11

tony19