How to use Vuex mapActions and mapMutations
Thank you for your continued support.
This article contains advertisements that help fund our operations.
Table Of Contents
I summarized how to use Vuex's mapActions and mapMutations.
⇨ Click here for the table of contents for Vue articles
How to use
Assumes that Actions are already written in Vuex.
I will explain in detail later, but let me summarize.
How to use mapActions
Sample.vue
<script>
import { mapActions } from "vuex"
export default {
methods: {
...mapActions("util", ["test"]),
// util is the module name (can be freely decided)
// test is the function name written in Actions
},
created() {
this.test() // you can call it with just this description
},
}
</script>
You can now use this.
How to use mapMutations
<script>
import { mapMutations } from "vuex"
export default {
methods: {
...mapMutations("util", ["test"]),
// util is the module name (can be freely decided)
// test is the function name written in Mutations
},
created() {
this.test() // you can call it with just this description
},
}
</script>
Why use mapActions
By using mapActions, you can call it in a very simple way when actually calling it,
this.test()
If you don't use mapActions,
Actions
methods: {
this.$store.dispatch("util/test")
}
Mutations
methods: {
this.$store.commit("util/test")
}
It will become like this.
That's the end of the main content, but if you're still not sure about implementing Vuex itself, please continue reading.
Related articles
Defining Vuetify's Snackbar in Vuex to reuse it anywhere
How to separate store processing in Vue.js into files
【Solved with rootState】Stuck after dividing the store into files in vuex and transferring data
Overall implementation of Vuex
Let's check the overall implementation of Vuex.
━ store
┣ index.js
┗ modules
┗util.js
index.js
import Vue from "vue"
import Vuex from "vuex"
import util from "./modules/util"
Vue.use(Vuex)
export default new Vuex.Store({
modules: {
util,
},
})
util.js
const getters = {}
const state = {}
const mutations = {
test(state) {
console.log("test")
// you can change the state by writing state.test = 'test'
},
}
const actions = {
test({ commit }) {
console.log("test")
// commit('test') can run the test function in Mutations
},
}
export default {
namespaced: true, // required
state,
mutations,
getters,
actions,
}
Challenges of Vuex
mapActions and mapMutations have very similar capabilities.
Therefore,
- Call with mapActions when calling
- Write only the description to change the state in Mutations
By deciding this,
You can avoid confusion between "that's with mapMutations" and "that's with mapActions".
I think this depends on the project's policy, so please take it as a reference.
Summary
That's all.
I extracted it from the various patterns written in the official documentation here.
I hope it can be a reference for someone.
If you have complaints or corrections, please DM me on Twitter below.
That's all!