GCien
GCien

Reputation: 2349

How should I use v-model and v-on:change for an input select correctly?

So my searches on this topic are coming back with various GitHub issue tracking discussions from a while ago.

Essentially, I have the following Bootstrap Select input:

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

Firstly, excuse the mix of v- and : binding syntax. Secondly, the on-change binding is triggering the countryCountyConfiguration function, I have stripped it back to its simplest form for ease of debugging:

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

Effectively, the best was I can describe this issue is that v-on:change="countryCountyConfiguration" is always one step behind v-model="selectedCountry" ... always displaying the previous v-model binding. However, I really need the on change to feedback on country - such that if X country is chosen I will provide a dynamic choice of Counties and/or States.

I was wondering, how would I get v-on:change="countryCountyConfiguration" and v-model="selectedCountry" to work in conjunction?

Upvotes: 3

Views: 8206

Answers (2)

Kyeseung Kim
Kyeseung Kim

Reputation: 1

what about do it like this

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

using '$nextTick'..

Upvotes: 0

Harshal Patil
Harshal Patil

Reputation: 20950

Ideally, that should not happen. It seems to be a problem with the component. It would happen because change event is firing before the event which is responsible for v-model. By default v-model uses :value and v-on:input as value and event pair.

In your case, you should resort to explicit one-way data binding and avoid the use of v-model as:

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

Your countryCountyConfiguration will be:

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

Upvotes: 4

Related Questions