vue computed "TypeError: [] is not a function" 的问题(记录一下咯~)

88 阅读1分钟

computed中使用forEach会报 "TypeError: [] is not a function" 这个错误

computed: {
  ...mapState(namespace, {
    countingTask: (state) => state.countingTask
  }),
  countingTaskCheckWarehouse () {
    let warehouse = []
    (this.countingTask.checkWarehouse || []).forEach((item) => {
      warehouse.push(item.name)
    })
    let warehouseStr = warehouse.join(',')
    return warehouseStr
  }
}

image.png

解决方案:

  1. 使用 for
computed: {
  ...mapState(namespace, {
    countingTask: (state) => state.countingTask
  }),
  countingTaskCheckWarehouse () {
    let warehouse = []
    for (let i = 0; i < this.countingTask.checkWarehouse.length; i++) {
      warehouse.push(this.countingTask.checkWarehouse[i].name)
    }
    let warehouseStr = warehouse.join(',')
    return warehouseStr
  }
}
  1. 使用 for...of...
computed: {
  ...mapState(namespace, {
    countingTask: (state) => state.countingTask
  }),
  countingTaskCheckWarehouse () {
    let warehouse = []
    for (let item of this.countingTask.checkWarehouse) {
      warehouse.push(item.name)
    }
    let warehouseStr = warehouse.join(',')
    return warehouseStr
  }
}
  1. 使用 map
computed: {
  ...mapState(namespace, {
    countingTask: (state) => state.countingTask
  }),
  countingTaskCheckWarehouse () {
    return (this.countingTask.checkWarehouse || []).map(x => x.name).join(',')
  }
},