Vuejs 模板:“无法读取 null 的属性”,但已定义数组

问题描述 投票:0回答:1

我想在我的 Vuejs 模板中显示数组元素。

我从 API 获取数据,将它们格式化为带有函数的关联数组,然后尝试在模板中显示:

export default {
  components: {
    DefaultHeader,
    DefaultFooter
  },
  data() {
    return {
      info: null,
    };
  },
  mounted() {
    this.refreshData();
  },
  methods: {
    refreshData() {
      infoService.getInfo(this.$route.params.id)
        .then(response => {
          this.info = FormatHelper.BInfoFormat(response.data);
        })
        .catch(e => {
          console.log(e);
        });
    }
  }
}

当我尝试使用以下代码访问第一个元素“名称”时:

{{ this.info.name }}

我收到错误:

未捕获(承诺中)类型错误:无法读取 null 的属性 (读“名字”)

但是当我在代码中的完全相同的位置尝试这个时:

{{ this.info }}

我可以看到数组已定义:

{ "name": "B3", "call": "about", "G": "H" }

此外,当我尝试控制台登录我的 Mounted() 组件函数时,我得到了正确的数据:

console.log(this.info.name)

有关信息,在 Mounted() 函数中执行操作时的对象类型:

console.log(this.info)

是:

Proxy(Object) {name: 'B3', call: 'about', G: 'H'}

我尝试访问数据的方式出了什么问题导致出现此错误?

javascript arrays vue.js vuejs3 associative-array
1个回答
0
投票

问题已解决,感谢评论:

在:

export default {
  components: {
    DefaultHeader,
    DefaultFooter
  },
  data() {
    return {
      info: null,
    };
  },
  mounted() {
    this.refreshData();
  },
  methods: {
    refreshData() {
      infoService.getInfo(this.$route.params.id)
        .then(response => {
          this.info = FormatHelper.BInfoFormat(response.data);
        })
        .catch(e => {
          console.log(e);
        });
    }
  }
}

替换:

  data() {
    return {
      info: null,
    };
  },

作者:

  data() {
    return {
      info: {},
    };
  },

空处的初始定义破坏了我试图在模板中使用的数组方法。

© www.soinside.com 2019 - 2024. All rights reserved.