Vuex store checkbox values in state object

I have posted this question before but no answers.

Hello everybody, Im new to Vuex and Vue Im trying to store a checkbox(true, false) value into my state object so that I later can use that specific value but its not working.

Right now Im getting this error: “Uncaught SyntaxError: Unexpected token ‘;’” Therefore Im not even seeing my checkbox, and very unsure of my piece of code is working.

https://jsfiddle.net/vbxp0ae7/2/

I have one example with Vue-Vuex-Bootstrap https://jsfiddle.net/Jayesh_v/zjsbocdL/ you can refer to it.
Looking at your code, it seems you are trying to do it with typescript and there are syntax issue calling vuex.

1 Like

Hi @Jayesh , thank you for your answer! 3 questions :slight_smile:
Why are you not using a actions object in your Vuex store to commit?
And also you are not using mapState and mapActions in your Vue component?
Also you not using a click event in your b-form-checkbox element why is this?

  1. Vuex Action is required when you have asynchronous operations, like api calls. If you just wanted to change the variable state, you can directly call the mutation, just like in this case.
  2. You can use mapState or mapActions as an alternative to calling state or actions.
  3. Do not use click event for b-form-checkbox, you can use v-model or :value-field prop with @input event.

I have modified the above example to show you the uses. https://jsfiddle.net/Jayesh_v/z4h20mce/

1 Like

Alright thank you so much @Jayesh ! :slight_smile:

Lets say that I have a API call, would this be the correct way of doing it:

The store:

const store = new Vuex.Store({
  state: {
  	status: false
  },
  mutations: {
  	setStatus (state, value) {
    	state.status = value;
    }
  },
  actions:{
     setStatusAction(context, status){
          context.commit( 'setStatus' status );
    }
  }
});

Vue Component:

new Vue({
  el: '#app',
  store,
  computed: {
        ...Vuex.mapState( 'store', {  
            status(state) {
              return state.status 
            } 
         }),
  }
  
  methods: {
     ...Vuex.mapActions( 'store', {  
         set: 'setStatusAction'
        }),
  }
});

<div id="app">
  <div>
    <b-form-checkbox id="checkbox-1" :value-field="status" name="checkbox-1" @input="set">
      I accept the terms and use
    </b-form-checkbox>
    <div>State: <strong>{{ status }}</strong></div>
  </div>
</div>

Your syntax is not correct for calling mapState and mapActions. there is no first parameter store for mapState or mapActions

computed: {
  ...Vuex.mapState(['status'])
}
or
computed: {
   ...Vuex.mapState({
       status: state => state.status
   })
}

Actions

checkbox event @input="setStatusAction"

methods: {
  ...Vuex.mapActions(['setStatusAction'])
}

or

when @input="set"

methods: {
  ...Vuex.mapActions({
      set: 'setStatusAction'
   })
}
1 Like