Search code examples
javascriptvue.jsvuejs2vuexbootstrap-vue

Prevent Select Input value change conditionally


I have this vue component:

<template>
    <div id="OrderTypeSelect" class="order-type-select">        
         <b-form-select v-model="curDocType" :options="options" class="mb-3">
        </b-form-select>        
    </div>
</template>

the value of the select input is bound to the Vuex store like this:

computed: {
        curDocType: {
            get () {
                return this.$store.state.curDocType
            },
            set (value) {
                 this.$store.commit('setcurDocType', value)                
            }
        }
    }

What I can't figure out is how to conditionally prevent the select value from changing. I've tried this:

computed: {
        curDocType: {
            get () {
                return this.$store.state.curDocType
            },
            set (value) {
                if (this.$store.state.curOrder == ""){
                    this.$store.commit('setcurDocType', value)
                }
                else{
                    console.log("Debe descartar");
                    this.curDocType.get() //This throws error!
                }
            }
        }
    }

Even if I don't commit the value to the store, the value in the input field is changed.

I need to call get() again (or something else) to make this binding persistent when my condition is triggered:

if (this.$store.state.curOrder != "") {
  //Do not modify store and return the input selection to it's previous value
} 

Solution

  • In your case i recommend to use a data object item called curDocType and watch it instead of using computed property :

     <b-form-select v-model="curDocType" :options="options" class="mb-3">
    

    data object :

      data(){
         return{
             curDocType:this.$store.state.curDocType
            };
           }
    

    watch property :

       watch:{
         curDocType(newval,oldval){
                if (this.$store.state.curOrder == ""){
                    this.$store.commit('setcurDocType', newval)
                }else{
                 this.$nextTick(() => {this.curDocType=this.$store.state.curDocType})
                }
             }
           }