Search code examples
vue.jsvue-componentvuex

Vue 3 checkbox bound to vuex store will not check after unchecked


I have a form component with a check box that needs to be true/false. The form is bound to a vuex store.

I set the initial value to true and it is checked on load. But when I uncheck it the value changes to "on" and i can not re-check it.

<div class="form-group form-check">
        <input type="checkbox" name="product_inventory_item" class="form-check-input" @change="updateWorkingProductDataField('product_inventory_item', $event.target.value)" v-model="workingProductData.product_inventory_item"/>
        <label class="form-check-label">Inventory Item?</label>
</div>

My Vuex Store:

export const state = {
    workingProductData: {
        product_inventory_item: true,

        //This value is changed to "on" when the checkbox is clicked
        //The check box will no longer check after it is unchecked
        //How do i set the value to true/false based on checked or unchecked?

    }
};

export const getters = {
    workingProductData: state => {
        return state.workingProductData;
    }
};

export const mutations = {
    updateWorkingProductDataProperty(state, payload){
        state.workingProductData[payload.field] = payload.value;
    },
};

export const actions = {
    updateWorkingProductData({commit, state}, payload){
        commit('updateWorkingProductDataProperty', payload);
    },
};

My Component Object:

export default {
    name: "ProductForm",
    props: {
        editing: {
            type: Boolean,
            required: false,
            default: false,
        },
        categoryID: {
            type: Number,
            required: false,
            default: null
        }
    },
    data(){
        return {
        }
    },
    emits: ['updateProductData', 'addNewProductData'],
    methods:{
        updateWorkingProductDataField(field, value) {
            this.$store.dispatch('product/updateWorkingProductData', {field: field, value: value});
        },
        submitProductForm(){
           
        },
        clearFormData(){

        }
    },
    computed:{
        workingProductData: function() {
            return this.$store.getters['product/workingProductData'];
        },
        productCategories(){
            return this.$store.getters['productCategory/productCategories'];
        }
    }
}

Thanks for any help!!


Solution

  • $event.target.value is giving on, instead you need to use $event.target.checked, which gives true or false. So change the template to:

    @change="updateWorkingProductDataField('product_inventory_item', $event.target.checked)"