【问题标题】:Prevent Select Input value change conditionally防止有条件地选择输入值更改
【发布时间】:2019-05-13 15:36:26
【问题描述】:

我有这个 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>

选择输入的值绑定到 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
} 

【问题讨论】:

  • 你试过reurn this.$store.state.curDocType而不是this.curDocType.get()
  • `return this.$store.state.curDocType 不行,输入值就这样改了。不知道 set() 是否应该返回一个值。无论如何都不是根据文档:vuex.vuejs.org/guide/forms.html#two-way-computed-property

标签: javascript vue.js vuejs2 vuex bootstrap-vue


【解决方案1】:

在您的情况下,我建议使用名为 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})
            }
         }
       }

【讨论】:

    【解决方案2】:

    试试&lt;b-form-select v-model="curValue" @input="setValue" :options="options" class="mb-3"&gt; 其中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})
            }
        }
    }
    

    【讨论】:

    • 对不起,这也与我的原始代码具有相同的效果。输入选择值可以更改
    • 抱歉,有错字,请立即尝试。注意你在组件上使用了v-model
    • 恐怕我仍然有相同的结果:(在这些更改之后也无法正常工作
    • 我可以看到您的示例正在运行,可能是我正在使用的库(bootstrap-vue)或混合使用的 Vuex 存储的问题
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-18
    • 2015-04-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多