Search code examples
vue.jsvuejs3nuxt.jsvuex4

How to bring the payload stored via mutations


adding a number using @click event but not working.

Counter.vue

<script>
import { mapState, mapMutations  } from "vuex"
export default {
  data() {
    return{
      //payload
      value: 1,
    }
  },
  computed: {
    ...mapState(["counter"])
  },
  method: {
    ...mapMutations(["addToCounter"])
  }
}
</script>

on main.js

import { createApp } from 'vue'
import { createStore } from "vuex";

import App from './App.vue';
const store =  createStore({
  state() {
    return {
      counter: 11,
    }
  },
  mutations: {
    addToCounter(state, payload){
      state.counter = state.counter + payload;
    }
  }
})

//connecting store to the application
const app = createApp(App)

//using the store that is created
app.use(store)

app.mount('#app')

There is no error but addToCounter isn't working while the value is supposed to be added to the counter when @click is triggered.

When we click + button, the number above should be added


Solution

  • Please make an effort in formatting when posting your question.

    • It should be methods and not method.
    • What is main.js? There is no such file in Nuxt and you should not have to create your own store because it is already baked in: https://nuxtjs.org/docs/2.x/directory-structure/store
    • createApp and createStore are related to Vue3, hence not compatible with Vue2 (used by Nuxt as of right now)
    • you should not call a vuex mutation to update the state, but rather an action other you could have some issues.