如何正确使用v-model和v-on:change进行输入选择?

时间:2018-07-25 08:25:52

标签: vue.js vuejs2 v-model

因此,不久前,我在该主题上进行的搜索都伴随着各种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-和:绑定语法的混合使用。其次,按更改绑定正在触发countryCountyConfiguration函数,为了方便调试,我将其剥离为最简单的形式:

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

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

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

2 个答案:

答案 0 :(得分: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
    // ...
}

答案 1 :(得分:0)

这样做怎么样

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

使用“ $ nextTick”。

相关问题