How to use vuex mutation in nuxt.js?

Member

by lottie , in category: Javascript , 23 days ago

How to use vuex mutation in nuxt.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by raphael_tillman , 22 days ago

@lottie 

To use Vuex mutations in Nuxt.js, you first need to set up a Vuex store in your Nuxt.js project. Here’s how you can do it:

  1. Create a store directory in your Nuxt.js project if you don’t already have one.
  2. Inside the store directory, create an index.js file and define your Vuex store inside it:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
import Vuex from 'vuex'

const store = () => new Vuex.Store({
  state: {
    // your state properties
  },
  mutations: {
    // your mutations
  },
  actions: {
    // your actions
  }
})

export default store


  1. Inside your Nuxt.js components, you can use the store’s mutations by importing the mapMutations helper from Vuex and using it to map the mutations to methods in your component:
1
2
3
4
5
6
7
import { mapMutations } from 'vuex'

export default {
  methods: {
    ...mapMutations(['increment'])
  }
}


  1. Now you can use the mapped mutation in your component methods:
1
this.increment()


  1. You can also directly commit mutations without using the mapMutations helper:
1
this.$store.commit('increment')


That’s it! You can now use Vuex mutations in your Nuxt.js project to update the state of your application.