首页 > 解决方案 > 使用 VueJS 访问 JSON 子对象

问题描述

我目前有一个从 API 获取数据的 JavaScript 页面。问题是我无法访问service.statusgroup.name响应中的对象。

我收到此错误:“TypeError:service.statusgroup 为空”。但是当我删除时.name,我没有收到任何错误。

JSON响应

{
  "id": 2,
  "title": "Website",
  "description": "Website accessibility",
  "status": "0",
  "statusgroup": {
    "id": 1,
    "name": "Services",                     <-- Can't get this
    "created_at": "2021-03-14T17:08:15.204Z",
    "updated_at": "2021-03-14T17:40:29.739Z"
  },
  "created_at": "2021-03-14T15:06:18.524Z",
  "updated_at": "2021-03-14T17:42:22.235Z"
}

JavaScript 获取(VueJS)

export default {
  name: 'Status',
  mounted() {

    // Fetch data from API
    axios.get('http://localhost:1337/statuspages')
    .then((reponse) => {
      this.services = reponse.data
    })

  },
  data: function() {
    return {
      services: null,
    }
  },

显示响应

<template v-for="service in services">
    <v-list-item :key="service">
        {{ service.statusgroup.name }}
    </v-list-item>
</template>

标签: jsonapivue.jsfetchvuetify.js

解决方案


推荐阅读