首页 > 解决方案 > 创建要在多个方法中多次调用的函数

问题描述

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

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 写到最后的所有内容,我在多个方法中重复相同的内容,那么如何将所有那段代码放在一个函数中并在方法中调用该函数?

标签: javascriptfunctionvue.jsmethodsvuejs2

解决方案


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

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


推荐阅读