Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bootstrap vue select sending old value

I got this select code based on vue bootstrap:

<b-form-select v-model="selectedgroup" class="mb-3"  @change="searchSubGroup()">
    <option :value="null">Select a group</option>
    <option v-for="group in groupItem" :value="group.id">
        {{group.nome}}
    </option>
</b-form-select>  

When the searchSubGroup() method is called by @change event, the @change event pass a old value of selectedgroup. Example: If i click in option with value = 1 first, the method will call selectedgroup as null, then if i click again in another option with value = 2, the method will call selectedgroup as 1.

searchSubGroup(){ 
  this.axios.get("http://chart.solutions/public/api/produto/subgroup/search/" + this.selectedgroup + "/").then(response => {
        if (response.data.erro) {
            //console.log("subgroup doesnt exist")
        }else{
            this.subGroupItem = response.data;
        }
    })
} 
like image 604
SkullFire Avatar asked Nov 01 '18 17:11

SkullFire


2 Answers

You should call your searchSubGroup method without the parentheses. This will automatically pass the newly selected value to your method ..

<b-form-select v-model="selectedgroup" class="mb-3"  @change="searchSubGroup">
    <option :value="null">Select a group</option>
    <option v-for="group in groupItem" :value="group.id">
        {{group.nome}}
    </option>
</b-form-select>

Then in your method you should do the following ..

searchSubGroup(value){ 
  this.axios.get("http://chart.solutions/public/api/produto/subgroup/search/" + value + "/").then(response => {
        if (response.data.erro) {
            //console.log("subgroup doesnt exist")
        }else{
            this.subGroupItem = response.data;
        }
    })
} 
like image 73
Husam Ibrahim Avatar answered Nov 16 '22 18:11

Husam Ibrahim


You need to remove the () from the @change call as such:

@change="searchSubGroup"

If you leave the () set, then the function is getting called when the component is getting build and the "selectedgroup" is still not defined, thus calling with null

v-model works based on @change so the event is getting fired twice. The selectedGroup method is getting called BEFORE the change method that updates the v-model data. Which is why the value was the "old one".

Even though the other answer is still a correct way of avoiding the issue, it does not explain exactly why this is happening.

Heres another solution:

  1. Remove your @change call from the b-form-select
  2. Add a "watched" property

    watch: { selectedgroup(value) { this.searchSubGroup(); //OR you could remove the method and just call axios here }) }

like image 3
Marina Mosti Avatar answered Nov 16 '22 20:11

Marina Mosti