防止选择输入值有条件地更改

时间:2018-12-12 13:53:40

标签: javascript vue.js vuex

我有这个Vue组件:

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

select输入的值被绑定到Vuex存储,如下所示:

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

我不知道如何有条件地防止选择值更改。我已经尝试过了:

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

即使我不将值提交到商店,输入字段中的值也会更改。

当我的条件被触发时,我需要再次调用get()(或其他方式)以使此绑定保持不变:

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

2 个答案:

答案 0 :(得分:2)

在您的情况下,我建议使用一个名为curDocType的数据对象项并注意它,而不要使用计算属性:

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

数据对象:

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

观看属性:

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

答案 1 :(得分:2)

尝试<b-form-select v-model="curValue" @input="setValue" :options="options" class="mb-3"> 其中curValuedata中的变量,而setValue是方法:

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