Reputation: 115
I am currently faced with a situation where I add options to a select element via vuejs when the @change of that specific element is called.
The problem is that the new option is not 'registered' until I leave the function.
I made a jsfiddle to demonstrate this behaviour: https://jsfiddle.net/bz8361Lp/
In this demo, if a option in the select element is selected, a new option is added to the select. The console is still printing the old number of entries.
new Vue({
el: "#app",
data: {
data: ["test", "hallo", "bye"]
},
methods: {
onChange(event) {
console.log("test")
this.data.push("hello")
const element = document.getElementById("select")
console.log(element.options.length)
}
}
})
I am looking for some guidance on how I can avoid this problem, what I am doing wrong and what a best practice could be.
Thanks.
Upvotes: 0
Views: 272
Reputation: 22758
This is because Vue.js updates DOM not immediately but on the next event loop processing. You can read about this in detail here
You can check this by using nextTick
:
onChange(event) {
console.log("test")
this.data.push("hello")
this.$nextTick(() => {
const element = document.getElementById("select")
console.log(element.options.length)
});
}
Upvotes: 2
Reputation: 561
need to wait for the dom to render and then evaluate. You can find more information about what the function does '' this.$nextTick()
new Vue({
el: "#app",
data: {
data: ["test", "hallo", "bye"]
},
methods: {
onChange(event) {
console.log("test")
this.data.push("hello")
this.$nextTick(() => {
const element = document.getElementById("select")
console.log(element.options.length)
})
}
}
})
Upvotes: 0