1

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>
kissu
  • 40,416
  • 14
  • 65
  • 133
  • Hi, why would you need Vuex for tabs? Vuex should be used as a store for a global/broad state management. If it's for tabs, this should probably stay as a local state. – kissu Jul 09 '21 at 18:00
  • 1
    I wanted to be able to toggle the tabs from the components within it. I figured if I had all three button components locally that wouldn't be an issue but I wasn't able to get them to communicate with the component. I probably should have just emitted I think. Thanks again though – Guillermo Medel Jul 09 '21 at 19:47

1 Answers1

1

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>
kissu
  • 40,416
  • 14
  • 65
  • 133