Luis Rodriguez
Luis Rodriguez

Reputation: 277

How to execute method once for certain data value

I have a web app that goes through steps showing different content. I have a value of 'data: 0' in my data property and is incremented every time the next button is hit. A user is able to go back in steps to make changes if needed.

What I'm trying to do is have a method fire once when it hits a certain step. Can I use v-on:change to check for this specific data value and if so where would I place that handler? This method should only be fired the first time it hits the specific step to avoid issues when a user goes back.

data: {

 addedKeywords: false,
 newAds:[
  []
  ]
 },
 methods: {
 baseAds(){
  if(this.step3Base == false){
    this.newAds[0].push({
      id: 0,
      headline1: 'Headline 1',
      headline2: 'Headline 2',
      headline3: 'headline3',
      desc1: 'This is your description 1',
      desc2: 'This is your description 2',
      finalurl: 'www.finalURL.com',
      path1: '',
      path2: '',
      boolean: true
    })
    for(var x = 1; x < this.options.length; x++){
      this.newAds.push([]);
    }
  }
  this.step3Base = true;
 },
 restOfAds (){
  var length = this.options.length
  if(this.addedKeywords === false){
    for(var x = 1; x < length; x++){
      this.newAds[x].push({
        id: x,
        headline1: 'New',

      })
    }
    this.addedKeywords = true;
  }
 },
 lengthInput: function (){

  return this.options.length

}
},
watch: {
lengthInput: function(oldlength, newLength){
  if(newLength > oldlength && this.addedKeywords != false){
    for(var x = oldLength; x < newLength; x++){
      this.newAds.push([{
        id: x,
        headline1: 'New',

      }])
    }
  }

}
}

Upvotes: 0

Views: 43

Answers (1)

Dhananjai Pai
Dhananjai Pai

Reputation: 6015

You can use watchers [https://v2.vuejs.org/v2/guide/computed.html#Watchers] tp listen to changes in the value of a data variable and run a specific function when the steps reach a specified value. You can also create some flag variable and set it appropriately to prevent the function getting triggered again.

Upvotes: 1

Related Questions