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;
}
})
}
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;
}
})
}
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:
Add a "watched" property
watch: {
selectedgroup(value) {
this.searchSubGroup();
//OR you could remove the method and just call axios here
})
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With