【问题标题】:VueJS how to access a value in an array in json output of api call?VueJS 如何在 api 调用的 json 输出中访问数组中的值?
【发布时间】:2022-12-17 22:56:34
【问题描述】:

我正在从头开始写一个博客,前端和后端通过我制作的 API 进行通信,这是 JSON 输出:

{
    "status": true,
    "posts": [
        {
            "id": 2,
            "title": "a la zeub",
            "description": "zebi",
            "user_id": 1,
            "created_at": "2022-12-08T12:16:58.000000Z",
            "updated_at": "2022-12-08T12:16:58.000000Z"
        },
        {
            "id": 4,
            "title": "title2",
            "description": "thing",
            "user_id": 1,
            "created_at": "2022-12-08T12:39:15.000000Z",
            "updated_at": "2022-12-08T12:39:15.000000Z"
        }
    ]
}

我使用 VueJS 作为前端,当我想显示 API 响应的一个值时,我在 HTML 部分使用以下语法:

<p> {{ the name of the variable }} </p>

但它不起作用,如果我这样做:

<p> {{ posts.status }} </p>

它在 p 标签中返回“true”,但如果我尝试类似 posts.posts.id 或 posts.posts['id'] 的东西它根本不起作用,p 标签存在于源代码中但没有内容.我应该在括号之间写什么才能访问标题?

【问题讨论】:

  • 它是一个数组,你需要用 v-for 循环它,以访问它的第一项 {{ posts.posts[0].id }}
  • @LawrenceCherone 你好!首先,感谢您的回答,但仍然无法正常工作...这是我所做的:<div v-for="posts in posts" :key="posts.posts[0].id"> <p v-html ="posts.posts[0].id"></p> </div>
  • 是的,喜欢&lt;div v-for="item in posts.posts" :key="item.id"&gt; &lt;p&gt;{{ item.id }}&lt;/p&gt; &lt;/div&gt;,通知帖子是项目posts in posts 不会工作。

标签: json api vue.js variables


【解决方案1】:

同意@LawrenceCherone 并追求 cmets,你需要做这样的事情 -

为了准备一个示例,我在 data 属性中使用变量 posts 并将您的 JSON 输出分配给它。

<html>
<div id="app">
  <p v-for="(post, index) in posts.posts" :key="index">{{ post.title }}</p>
</div>

<!-- Don't forget to include Vue from CDN! -->
<script src="https://unpkg.com/vue@2"></script>
<script>
  new Vue({
    el: '#app', //Tells Vue to render in HTML element with id "app"
    data() {
      return {
        posts: {
         status: true,
         posts: [
          {
            "id": 2,
            "title": "a la zeub",
            "description": "zebi",
            "user_id": 1,
            "created_at": "2022-12-08T12:16:58.000000Z",
            "updated_at": "2022-12-08T12:16:58.000000Z"
           },
           {
            "id": 4,
            "title": "title2",
            "description": "thing",
            "user_id": 1,
            "created_at": "2022-12-08T12:39:15.000000Z",
            "updated_at": "2022-12-08T12:39:15.000000Z"
            }
         ]
        }
      }
    }
  });
</script>
</html>

【讨论】:

    猜你喜欢
    • 2021-12-23
    • 2021-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-17
    • 2020-09-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多