如何为某个数据值执行一次方法

How to execute method once for certain data value

我有一个网络应用程序,它通过显示不同内容的步骤。我的数据 属性 中有一个 'data: 0' 的值,每次按下下一个按钮时都会递增。如果需要,用户可以返回步骤进行更改。

我想要做的是让一个方法在达到某个步骤时触发一次。我可以使用 v-on:change 来检查这个特定的数据值吗?如果可以,我应该把那个处理程序放在哪里?此方法应仅在第一次达到特定步骤时触发,以避免用户返回时出现问题。

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',

      }])
    }
  }

}
}

您可以使用观察者 [https://vuejs.org/v2/guide/computed.html#Watchers] tp 监听数据变量值的变化,并在 steps 达到指定值时 运行 执行特定函数。您还可以创建一些 flag 变量并适当地设置它以防止再次触发该函数。