如何在vue js中从数组访问嵌套对象属性

amrnrhlw  于 2023-04-07  发布在  Vue.js
关注(0)|答案(4)|浏览(166)

这是我在DOM中得到的JSON响应

{ "resource": "services", "status": "success", "data": [ { "service_id": "0001", "service_name": "Buy Airtime", "service_type": "airtime" },  ] }

这就是我的模板

<li v-for="service in responseObject">
          {{ service }}
        </li>

这是我的脚本标签

<script>
import axios from "axios";
export default {
  data() {
    return {
      status: false,
      responseObject: {}
    };
  },
  async mounted() {
    try {
      let response = await axios.get("http://localhost:4000/api/blogs");
      this.responseObject = response.data;
    } catch (e) {
      console.log(e);
    }
  }
};
</script>

我如何显示

service_id and service_name in my template

我试过了

service.data[0].service_name

但我没有得到任何回应

z9smfwbn

z9smfwbn1#

这就是你所缺少的

response.data.responseObject

修改你的代码

async mounted() {
    try {
      let response = await axios.get("http://localhost:4000/api/blogs");
     this.responseObject = response.data.responseObject;
    } catch (e) {
      console.log(e);
    }
  }

然后在模板中

<li
            v-for="service in  responseObject.data"
            :key="service.service_id"
          >
            {{ service.service_name }} - {{ service.service_id }}
          </li>

您应该会看到输出

8tntrjer

8tntrjer2#

就这么做

<li v-for="service in responseObject">
     {{ service.service_id }} - {{service.service_name}}
</li>

因为service代表数组的一个元素

yk9xbfzb

yk9xbfzb3#

你可以通过在你的v-for语句中添加点符号来访问子“data”数组(“responseObject.data“)-

<ul>
      <li v-for="service in  responseObject.data"    :key="service.service_id">
        {{ service.service_name }}
      </li>
    </ul>

Codepen - https://codepen.io/bsod_/pen/wvYwBrj

yrdbyhpb

yrdbyhpb4#

您可以尝试打印response.data确认是否已获得正确的数据

相关问题