【问题标题】:Vue Javascript forEach loop inside methodVue Javascript forEach循环内部方法
【发布时间】:2020-12-01 16:05:32
【问题描述】:

我正在尝试添加多个图像,但我找不到让它工作的方法。

我有这个方法:

        imageAdd(e) {         
            e.forEach(function(e) {
            if (e.type == 'image/jpeg' || e.type == 'image/png')
            {
                this.images.push({
                    image: URL.createObjectURL(e),
                    imageData: e
                    })
            }
            })
   },

当我尝试推送到图像数组时,它给我带来了这个错误Cannot read property 'images' of undefined,尽管它是在我的数据中定义的。这里有什么问题?

【问题讨论】:

  • .forEach(/*...*/, this).forEach(/*...*/.bind(this) 或相关。
  • @ASDFGerte 或箭头函数,我猜。
  • True,或者使用for ... of 而不是.forEach,这通常更胜一筹

标签: javascript vue.js


【解决方案1】:

使用箭头函数而不是具有自己的this

 imageAdd(e) {         
            e.forEach((e) => {
            if (e.type == 'image/jpeg' || e.type == 'image/png')
            {
                this.images.push({
                    image: URL.createObjectURL(e),
                    imageData: e
                    })
            }
            })
   }

【讨论】:

  • 是的,让它像魅力一样工作。我使用了一个 for 语句,但这个对我来说看起来更干净。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-02-16
  • 1970-01-01
  • 2015-10-30
  • 2016-09-26
  • 2012-07-19
  • 1970-01-01
  • 2021-09-05
相关资源
最近更新 更多