Home > Software engineering >  Vue track the index of questions in form
Vue track the index of questions in form

Time:01-27

I have a component 'form' which contains of 6 questions. I have a plugin for generating phone input. The phone question is 3rd and I need to generate it only when the number of question is 3rd. I have an index of questions in data() hook, so I need to call function generateTel() when the index is 3 because this input creates in DOM only when the index is 3.

The html looks like:

<div v-if="index === 1" ></div>
<div v-if="index === 2" ></div>
<div v-if="index === 3" ></div>
<div v-if="index === 4" ></div>
<div v-if="index === 5" ></div>
<div v-if="index === 6" ></div>

How can I track when the index equals 3? Or maybe it isn't the best practice and I shouldn't use v-if?

Note: the Bergur's solution works but I had to add some corrections:

watch: {
 index(newVal) {
  if (newVal === 3) {
     let ref = this // to avoid this.generateTel() is not a function error
     setTimeout(function () { // add setTimeout to avoid calling method on undefined 
       ref.generateTel()
     }, 100)
  }
 }
}

CodePudding user response:

Use watch: https://vuejs.org/v2/guide/computed.html#Watchers

In your component:

watch: {
  index(newVal) {
    if (newVal === 3) {
       this.generateTel()
    }
  }
}
  •  Tags:  
  • Related