0

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.

1

2 Answers 2

2

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)
      });
    }
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, this has been really helpful.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.