Vuejs2 Vue computed属性:helper函数返回未定义,尽管已定义

Vuejs2 Vue computed属性:helper函数返回未定义,尽管已定义,vuejs2,vue-component,Vuejs2,Vue Component,我使用计算出的属性直径返回: -随机数随机化:真 -从数组中的对象返回的数字randomise:false 我确实有一个正在运行的实现,请参阅本文底部,但我想知道为什么更干净的实现不起作用。使用randomise:false时,直径返回未定义。为什么? 下面的实现是可行的,但是为什么我必须创建一个任意的属性来实现呢 diameter() { if (!this.vars || !this.passVars) { return math.randomInt(100, 1000) / (

我使用计算出的属性直径返回: -随机数随机化:真 -从数组中的对象返回的数字randomise:false

我确实有一个正在运行的实现,请参阅本文底部,但我想知道为什么更干净的实现不起作用。使用randomise:false时,直径返回未定义。为什么?

下面的实现是可行的,但是为什么我必须创建一个任意的属性来实现呢

diameter() {
  if (!this.vars || !this.passVars) {
    return math.randomInt(100, 1000) / (10 ** math.randomInt(0, 3))
  } else {
    this.populateValue('diameter')
    return this.blah
  }
}
问题是return元素.varValue是从forEach返回的,而不是populateValue

写这篇文章有多种方法。e、 g

对于this.vars的const元素{ 如果element.varName===variableName{ 返回元素.varValue } } 通过使用for/of循环,没有内部函数,因此返回的是您期望的函数

备选方案包括:

设值=null this.vars.forEachelement=> 如果element.varName===variableName{ value=element.varValue } } 返回值 或:

const match=this.vars.findelement=> return element.varName==variableName } 如果匹配{ 返回match.varValue }
正如Shirtle提到的,您从forEach返回,然后对该方法不返回任何内容。有一些方法可以解决这个问题,例如,分配一个局部变量并返回该变量。遗憾的是,无法获取forEach返回的值
computed: {
  diameter() {
    if (randomise) {
      return math.randomInt(100, 1000) //no problems
    } else {
      console.log(this.populateValue('diameter')) //undefined
      return this.populateValue('diameter')
    }
  }
}
methods: {
    populateValue(variableName) {
      this.vars.forEach(element => {
        if (element.varName === variableName) {
          console.log(element.varValue) //25.8
          return element.varValue
        }
      })
    }
  }
diameter() {
  if (!this.vars || !this.passVars) {
    return math.randomInt(100, 1000) / (10 ** math.randomInt(0, 3))
  } else {
    this.populateValue('diameter')
    return this.blah
  }
}
populateValue(variableName) {
  this.vars.forEach(element => {
    if (element.varName === variableName) {
      this.blah = element.varValue
    }
  })
}