创建一个函数,在多个方法中多次调用

时间:2021-01-07 09:02:02

标签: javascript function vue.js methods vuejs2

大家好,新年快乐!我需要一个程序,我需要用多种方法重复几次。我会给你写一个简短的例子:

method1() {
  //I DO THINGS

  const controlArray = []; 
  this.daySelected.forEach((element) => {
    
    const tStart = element.time.map((t) => t.startIsGreater); 

    if (tStart.includes(true)) {
      
      controlArray.push(tStart); 
      this.setNewEventInfoRequired(false); 
      this.setAlertWarning(true); 
    }
  });
},

method2() {
  //I DO OTHER THINGS DIFFERENT FROM THE FIRST METHOD

  const controlArray = []; 
  this.daySelected.forEach((element) => {
    

    const tStart = element.time.map((t) => t.startIsGreater); 

    if (tStart.includes(true)) {
      controlArray.push(tStart); 
      this.setNewEventInfoRequired(false); 
      this.setAlertWarning(true); 
    }
  });
},
 // and then I repeat the same with other methods (methodFoo, methodBar, etc...)

我从 const controlArray 到最后写的所有内容,我在多个方法中都重复相同的内容,那么如何将所有这些代码放在一个函数中,并在方法中调用该函数?

2 个答案:

答案 0 :(得分:1)

只需将通用代码放在一个方法中,然后在每个方法中调用它:

runCommonFunc(){ // give it a significative name
     const controlArray = []; 
  this.daySelected.forEach((element) => {
    

    const tStart = element.time.map((t) => t.startIsGreater); 

    if (tStart.includes(true)) {
      controlArray.push(tStart); 
      this.setNewEventInfoRequired(false); 
      this.setAlertWarning(true); 
    }
  });
},

method1(){
//I do things
this.runCommonFunc()
},

method21(){
//I do things
this.runCommonFunc()
}

答案 1 :(得分:0)

创建一个新方法,您将使用相同的功能,然后将此方法内部调用到其他方法中。

这里我创建了 helperMethod,它被调用到 method1method2

helperMethod(){
 const controlArray = []; //creo un array che conterrà elementi true
  this.daySelected.forEach((element) => {
    //per ogni elemento all'interno dell'array principale daySelected

    const tStart = element.time.map((t) => t.startIsGreater); //mappo l'elemento che contiene la proprietà startIsGreater

    if (tStart.includes(true)) {
      //se l'elemento mappato contiene true
      controlArray.push(tStart); //lo inserisco dentro l'array di controllo
      this.setNewEventInfoRequired(false); //il pulsante create scompare
      this.setAlertWarning(true); //l'alert appare
    }
  });
},
method1(){
this.helperMethod();
},
method2(){
this.helperMethod();
}
相关问题