vue.jsnuxt.jsmutation-eventsvue-dynamic-components

Mutating Nuxt Component


I've been trying to learn vuex for weeks now (I've seen dozens of tutorials and they only go over the counter example). I'm slow and still can't grasp how to do this.
My idea is to be able to switch tabs between components. I know that I'm supposed to use an action to activate the mutation (which I haven't been able to do) but the mutation should still work on the button press I think?

My question is how can I properly set up a mutation that passes a component value on a button click?
Also i'd like to know if my component toggling idea is even going to work or if there's a better way of doing this.

SignUp.vue

<template>
  <keep-alive>
    <component :is="component" />
  </keep-alive>
</template>

<script>
import SignUpOne from "../components/SignUpOne.vue"
import SignUpTwo from "../components/SignUpTwo.vue"
import SignUpThree from "../components/SignUpThree.vue"

export default {
components: {
    SignUpOne,
    SignUpTwo,
    SignUpThree,
  },
  computed: {
    ...mapState([
      'component',
    ])
  },
}
</script>

store/index.js

export const state = () => ({
  component: "SignUpOne",
})

export const mutations = () => ({
  changePage(state, payload) {
    state.component = payload.value;
  }
})

SeperateComponent.vue

<template>
  <button @click="changePg">Button</button>
</template>

<script>
export default {
  methods: {
    changePg() {
      this.$store.commit({
        type: 'changePage',
        value: "SignUpTwo"
       });
    },
  },
}
</script>

Solution

  • You will need something like this

    SignUp.vue

    <script>
    import { mapState } from 'vuex'
    export default {
    ...
    

    store/index.js

    ...
    
    export const mutations = () => ({
      CHANGE_PAGE(state, newComponentName) {
        state.component = newComponentName;
      }
    })
    
    export const actions = () => ({
      updateComponentName({ commit }, componentName) {
        commit('CHANGE_PAGE', componentName)
      },
    })
    

    SeperateComponent.vue

    <template>
        <div>
          <button @click="updateComponentName('SignUpOne')">Button</button>
          <button @click="updateComponentName('SignUpTwo')">Button</button>
          <button @click="updateComponentName('SignUpThree')">Button</button>
        </div>
    </template>
    
    <script>
    import { mapActions } from 'vuex'
    
    export default {
      methods: {
        ...mapActions(['updateComponentName']),
      },
    }
    </script>