我有一个简单的应用程序,用户选择一个人,vue 为该用户的帖子进行 api 调用。每个帖子都有自己的评论。这全部来自 https://jsonplaceholder.typicode.com/ 评论部分始终是空的。
代码笔是 here
我的html
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<div id='app'>
<div v-if='isError'>
There was an error
</div>
<div v-else-if='isLoading'>
Loading
</div>
<div v-else>
<select v-model="selectedUser">
<option v-for="person in info" v-bind:value="person"> {{person.name}}</option>
</select>
</div>
<div class="posts">
<div v-if="isLoadingPosts">
Loading...
</div>
<div v-else>
<ul>
<li v-for="post in postData">
<p>
{{ post.body }}
</p>
<button v-bind:id='post.id' v-on:click='getComments'>
View Comments
</button>
</li>
</ul>
</div>
</div>
<div class="comments">
<p>
{{ commentData }}
</p>
</div>
</div>
JS逻辑
var app = new Vue({
el: '#app',
data: {
info : null,
isLoading : true,
isError : false,
selectedUser : '',
postData : null,
isLoadingPosts : true,
commentData : null,
},
watch : {
selectedUser : function () {
axios
.get('https://jsonplaceholder.typicode.com/posts?userId=' + this.selectedUser.id)
.then(response => (this.postData =response.data))
.catch(error=> {console.log(error)})
.finally(() => this.isLoadingPosts = false)
}
},
methods : {
getComments : function (){
axios
.get('https://jsonplaceholder.typicode.com/posts/' + this.id + '/comments')
.then(response => (this.commentData =response.data))
}
},
mounted () {
axios
.get('https://jsonplaceholder.typicode.com/users')
.then(response => (this.info = response.data))
.catch(error => {console.log(error);this.isError = true})
.finally(() => this.isLoading = false)
}
})
除了注释部分总是返回空对象之外,一切正常。我也觉得我的代码是重复的,任何更正将不胜感激。
最佳答案
所以这个方法有几个问题:
getComments : function (){
axios
.get('https://jsonplaceholder.typicode.com/posts/' + this.id + '/comments')
.then(response => (this.commentData =response.data))
}
}
首先,其中的 this.id
将在组件本身上查找 id 属性,而不是您尝试在按钮中绑定(bind)的 id。
尝试将按钮代码更改为:
<button v-on:click='getComments(post.id)'>View Comments</button>
然后方法是:
getComments : function (id){
axios
.get('https://jsonplaceholder.typicode.com/posts/' + id + '/comments')
.then(response => (this.commentData =response.data))
}
}
此外,您可能想为其他 axios 调用添加一个 .catch()
处理程序,就像您的 id 一样。
关于javascript - vuejs 使用属性绑定(bind)显示 API 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53599359/