我有一个来自API的JSON:
{"users":
[
{"id":1,"name":"Adam"},
{"id":2,"name":"Barry"}
],
"announcements":
[
{"id":1,"content":"blah blah"},
{"id":2,"content":"ya ya"}
]
}
如何让vue资源获取这些数组,并将它们分别放入users
和announcements
中,以便在视图中循环?
我的脚本:
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()
}
根据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>