【问题标题】:How should I use v-model and v-on:change for an input select correctly?我应该如何正确使用 v-model 和 v-on:change 进行输入选择?
【发布时间】:2019-01-01 23:53:43
【问题描述】:

所以我在这个主题上的搜索返回了不久前的各种 GitHub 问题跟踪讨论。

基本上,我有以下 Bootstrap Select 输入:

 <b-form-text id="countrySelectionHelp" class="text-white my-1">Country: <span class="text-danger">*</span></b-form-text>
 <b-form-select id="countrySelection" v-on:change="countryCountyConfiguration" v-model="selectedCountry" size="sm" aria-describedby="countrySelectionHelp" required>
   <option :value="null">Please select an option...</option>
   <option v-for="country in countrySelections" :value="country.value" :key="country.value">{{ country.name }}</option>
 </b-form-select>

首先,请原谅 v- 和 : 绑定语法的混合。其次,on-change 绑定会触发 countryCountyConfiguration 函数,为了便于调试,我将其剥离为最简单的形式:

...
    },
    countryCountyConfiguration() {
      console.log(this.selectedCountry);
    },
...

实际上,我能描述这个问题最好的是v-on:change="countryCountyConfiguration" 总是比v-model="selectedCountry" 落后一步……总是显示以前的 v-model 绑定。但是,我确实需要更改国家/地区的反馈 - 这样,如果选择 X 国家/地区,我将提供县和/或州的动态选择。

我想知道,如何让 v-on:change="countryCountyConfiguration"v-model="selectedCountry" 协同工作?

【问题讨论】:

    标签: vue.js vuejs2 v-model


    【解决方案1】:

    理想情况下,这不应该发生。这似乎是组件的问题。这是因为change 事件在负责v-model 的事件之前触发。默认情况下,v-model 使用 :valuev-on:input 作为值和事件对。

    在您的情况下,您应该使用显式的单向数据绑定,并避免使用 v-model 作为:

    <b-form-select v-on:change="countryCountyConfiguration($event)" :value="selectedCountry">
        <!-- Some other code -->
    </b-form-select>
    

    您的countryCountyConfiguration 将是:

    countryCountyConfiguration(newSelectedCountry) {
        // THIS IS IMPORTANT
        this.selectedCountry = newSelectedCountry;
        // DO REST OF THE STUFF HERE
        // ...
    }
    

    【讨论】:

    • 应该注意,你可以简单地调用v-on:change="countryCountyConfiguration",因为b-form-select默认发送新值,不管你放什么参数,甚至没有参数。即使您将$event 作为参数传递,它也不会发送实际事件。不幸的是,似乎没有办法使用b-form-select 访问实际事件。开发人员的一个非常奇怪的选择。
    【解决方案2】:

    这样怎么样

    countryCountyConfiguration() {
      this.$nextTick(() => {
        //selectedCountry must be in 'v-model'
        console.log(selectedCountry)
      });
    }

    使用“$nextTick”..

    【讨论】:

      猜你喜欢
      • 2020-12-03
      • 2019-04-30
      • 2018-12-14
      • 2019-01-27
      • 2022-01-09
      • 2021-08-23
      • 2021-10-23
      • 2018-06-29
      • 2020-03-13
      相关资源
      最近更新 更多