使用 Vuejs 从 Wordpress Api 获取帖子
Fetch posts from Wordpress Api with Vuejs
我正在尝试使用 Vuejs 从 WP API 获取帖子标题,但控制台向我抛出错误
Cannot read property 'rendered' of undefined"
我不知道是什么问题。这是帖子组件:
<template>
<div class="posts">
<h1>Posts</h1>
<ul>
<li v-for="post in posts" :key="post.id">
{{ post.title.rendered }}
</li>
</ul>
</div>
</template>
<script>
export default {
mounted() {
this.getPosts();
},
data() {
return {
postsUrl: 'http://localhost:8080/wp-json/wp/v2/posts',
posts: [],
postsData: {
per_page: 10,
page: 1
},
}
},
methods: {
getPosts() {
axios.get(this.postsUrl, {params: this.postsData})
.then((response) => {
this.posts = response;
this.configPagination(response.headers);
})
.catch( (error) => {
console.log(error);
});
},
}
}
</script>
axios
中的 response
对象包含多个属性,例如 headers
、status
和 data
,在您的情况下,您的帖子是 data
属性, 所以设置 this.posts = response.data;
:
.then((response) => {
this.posts = response.data;
this.configPagination(response.headers);
})
我正在尝试使用 Vuejs 从 WP API 获取帖子标题,但控制台向我抛出错误
Cannot read property 'rendered' of undefined"
我不知道是什么问题。这是帖子组件:
<template>
<div class="posts">
<h1>Posts</h1>
<ul>
<li v-for="post in posts" :key="post.id">
{{ post.title.rendered }}
</li>
</ul>
</div>
</template>
<script>
export default {
mounted() {
this.getPosts();
},
data() {
return {
postsUrl: 'http://localhost:8080/wp-json/wp/v2/posts',
posts: [],
postsData: {
per_page: 10,
page: 1
},
}
},
methods: {
getPosts() {
axios.get(this.postsUrl, {params: this.postsData})
.then((response) => {
this.posts = response;
this.configPagination(response.headers);
})
.catch( (error) => {
console.log(error);
});
},
}
}
</script>
axios
中的 response
对象包含多个属性,例如 headers
、status
和 data
,在您的情况下,您的帖子是 data
属性, 所以设置 this.posts = response.data;
:
.then((response) => {
this.posts = response.data;
this.configPagination(response.headers);
})