【问题标题】:Cannot read property Array of undefined Vue无法读取未定义 Vue 的属性数组
【发布时间】:2021-01-14 03:03:00
【问题描述】:

我正在尝试从 firebase 存储中获取 URL,我只是坚持将它们推送到我的数组,以便稍后可以使用 v-for 来显示图像。

我搜索过 SO,人们提到绑定是一种解决方案。为了让您了解,这是我的代码:

export default {
  data() {
    return {
      items: [],
    };
  },
  mounted() {
    // Points to the root reference
    var storageRef = firebase.storage().ref();

    // Points to 'images'
    var listRef = storageRef.child("uploads");

    // Find all the prefixes and items.
    listRef.listAll().then(function (res) {
        res.prefixes.forEach(function (folderRef) {
          console.log(folderRef);
        });
        res.items.forEach(function (itemRef) {
          const data = {
            id: storageRef.child(itemRef.fullPath).getDownloadURL(),
          };
           
        this.items = this.items.bind(this) //this is the line that I just added
          this.items.push(data); //this is the line that generates the error
        });
      })
      .catch(function (error) {
        console.log(error);
      });
  },
};

我的控制台返回TypeError: Cannot read property 'items' of undefined

我是 vue 新手,这里发布的大部分内容都是有角度的,它并不能真正帮助我弄清楚如何解决我的错误。我该怎么办? 感谢您花时间阅读。

【问题讨论】:

  • 我有点不同意近距离投票的链接问题,答案没有给出真正的解释。这里的问题是你在你的 sn-p 中使用function(),函数有他自己的函数范围。在此范围内,您无权访问范围之外的对象(在您的情况下为this)。 (相对)新的匿名函数解决了这个问题。只需将所有function ( ... ) 调用更改为(...) => { } 即可。祝你好运!
  • 非常全面的解释。问题->原因->解决方案。谢谢你
  • @S.Visser 抱歉,我重新打开了您可以发表评论作为答案的问题

标签: javascript vue.js


【解决方案1】:

您的 items 数组范围在数据函数中,因此当您必须声明为全局时,您不能在其他函数中使用此 items 数组

【讨论】:

    【解决方案2】:

    绑定应该在forEach 回调函数上。 Function.prototype.bind()

    forEach(callbackfn.bind(this))
    

    在参数中发送这个:

    forEach(callbackfn, this)
    

    或者使用箭头函数而不是到处绑定

        listRef.listAll().then( (res)=> {
            res.prefixes.forEach( (folderRef)=> {
              console.log(folderRef);
            });
            res.items.forEach( (itemRef)=> {
              const data = {
                id: storageRef.child(itemRef.fullPath).getDownloadURL(),
              };
               
              this.items.push(data); //this is the line that generates the error
            });
          })
          .catch(function (error) {
            console.log(error);
          });

    【讨论】:

    • 这不是完全相同的问题。我不知道为什么@BoussadjraBrahim 关闭它。在这里,您以错误的方式使用了bind(this),不,您不应该像他回答的那样使用箭头功能。还有更多选择。
    猜你喜欢
    • 2019-01-30
    • 2021-09-14
    • 2021-03-29
    • 2019-06-06
    • 1970-01-01
    • 2020-02-23
    • 2022-06-28
    • 2021-11-11
    • 2020-10-09
    相关资源
    最近更新 更多