【问题标题】:Vue-Resource: How to get and show multiple arrays from JSONVue-Resource:如何从 JSON 获取和显示多个数组
【发布时间】:2019-03-30 08:22:30
【问题描述】:

我的 API 中有一个 JSON:

{"users":
[
    {"id":1,"name":"Adam"},
    {"id":2,"name":"Barry"}
],
"announcements":
[
    {"id":1,"content":"blah blah"},
    {"id":2,"content":"ya ya"}
]
}

如何让vue-resource获取这些数组,分别放入usersannouncements,以便在视图中循环播放?

我的脚本:

  export default {
    name: 'home',
    data: {
      users: [],
      announcements: []
    },
    methods: {
      fetchData () {
        this.$http.get('http://localhost:3000')
          .then(function (response) {
          // what do I put here to assign the response to users and announcements?
          })
      },
    },

    created: function () {
      this.fetchData()
    }

【问题讨论】:

  • 你可能想研究一下 axios - 我非常标准的 vue 并使这些类型的 http 请求更加友好。我从来没有处理过这样的原始 http 请求,但是使用 axios,您可以执行基本相同的代码,然后只需将响应分配给数组。
  • 至于调试,你可以把'console.dir(response);'这应该让您在浏览器控制台中了解 http 请求返回给您什么以及您可以分配什么。

标签: vue-resource


【解决方案1】:

根据 Jayem 的建议,我使用了 Axios:

安装然后引用 axios

import axios from 'axios'

Vue.prototype.$http = axios

使用 Axios

<script>
export default {
  data () {
    return { info: null, announcements: null, users: null }
  },
  mounted () {
    this.$http
      .get('http://localhost:3000/')
      .then(response => {
        (this.info = response.data)
        console.log(response.data.announcements)
        console.log(response.data.users)
      })
  }
}
</script>

在视图中添加:

<div v-for="announcement in info.announcements">
 {{ announcement.content }}
</div>
<div v-for="user in info.users">
 {{ user.name }}
</div>

【讨论】:

    猜你喜欢
    • 2013-10-09
    • 2020-05-15
    • 2018-07-31
    • 1970-01-01
    • 2019-11-01
    • 2020-07-24
    • 2019-12-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多