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?
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.
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.
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.
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 .
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With