Search code examples
javascriptvuejs2vuex

Hiding a paragraph using mutation in vuex?


i am trying to understand vuex and mutations and actions and i get that to change the state, you need to use a mutation but in practical it seems like maybe i am doing something wrong or i don't understand it well.

I am trying to hide this paragraph using a mutation from the store. I am using this real basic code to understand the concept of mutation.

  <template>
  <p v-if="this.$store.state.true">Hide this using Vuex </p>
  <v-btn @click="true = !true"> Click Me </v-btn>
  </template>

In my store. JS file

state : {
    true: false
  }

 mutations: {
    How would i go about creating a mutation????
    }

Thank you in advance


Solution

  • Try this

    mutations: {
        TOGGLE_TRUE (state) {
            state.true = !state.true
        }
    }
    
    <v-btn @click="$store.commit('TOGGLE_TRUE')"> Click Me </v-btn>
    

    I usually write mutations with uppercase snakecase, but you can change it to lowercase. It is case sensitive.

    To trigger a mutation, use commit and the mutation name as parameter. You can also pass an extra variable to commit 2nd parameter e.g:

    $store.commit('TOGGLE_TRUE', true)
    
    TOGGLE_TRUE (state, bool) {
        state.true = bool
    }
    

    and if you want to pass more data, use object and ES6 tree shaking

    person = {name: 'johndoe', age: 30}
    $store.commit('SET_PERSON', person)
    
    SET_PERSON (state, {name, age}) {
        state.name = name
        state.age = age
    }
    

    p.s You should find a better self-explanatory state name instead of just 'true', something like 'showParagraph' will do.