【发布时间】:2019-01-06 06:55:41
【问题描述】:
我正在尝试使用 VueJS 和 Axios 在页面上列出来自 API 的一组帖子。我面临的问题是需要通过针对该特定帖子的单独 API 调用来检索一段数据(帖子 url),并且它们在初始 API 调用中提供该数据的 url。我的第一部分工作得很好,但是当值 is 出现在 Vue devtools 中时,我无法在视图中渲染 href。
JS
const vm = new Vue({
el: '#app',
data: {
posts: []
},
mounted() {
this.getPosts();
},
methods: {
getPosts() {
axios.get("api_url")
.then((response) => {
this.posts = response.data.posts;
// Get URL for each post from separate API call
this.posts.map(post => {
axios.get(post.details_url+"&output=json")
.then((response) => {
post.official_url = response.data.post.pet_details_url;
}).catch( error => { console.log(error); });
});
}).catch( error => { console.log(error); });
}
}
});
HTML
<div id="app">
<div v-for="post in posts">
<a :href="post.official_url"> //href won't render
<h2>{{ post.title }}</h2>
<p>{{ post.text }}</p>
</a>
</div>
</div>
数据显示在 Vue DevTools 中
【问题讨论】:
-
添加
<div v-for="post in posts" :key="something_unique">可能会解决您的问题 -
感谢@TruongDang 的建议,但添加密钥并没有帮助。 ://
-
看起来很奇怪,我总是使用像
:href= "`/${post.official_url}`"这样的 href 并且它可以工作。确保您的post.official_url不为空 :"( -
我将其更改为该格式,现在出现了 href,但我得到了
<a href="undefined"></a>。所以我认为我的问题更多地与我在 JS 中的设置方式有关。