Jack Casas
Jack Casas

Reputation: 994

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
} 

Upvotes: 1

Views: 951

Answers (2)

Boussadjra Brahim
Boussadjra Brahim

Reputation: 1

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})
            }
         }
       }

Upvotes: 2

Igor
Igor

Reputation: 809

Try <b-form-select v-model="curValue" @input="setValue" :options="options" class="mb-3"> Where curValue is a variable in data and setValue is a method:

methods: {
    setValue(value) {
        if (this.$store.state.curOrder == "") {
            this.$store.commit('setcurDocType', value)
            this.curValue = value
        } else {
            console.log("Debe descartar");
            this.$nextTick(() => {this.curValue = this.$store.state.curDocType})
        }
    }
}

Upvotes: 2

Related Questions