使用Axios按slug筛选时WordPress REST API无法正常工作
问题分析与解决方案
我一眼就看出问题所在啦!你用 WordPress REST API 按 slug 请求文章时,接口返回的是一个数组(哪怕只有一篇匹配的文章),但你的模板里是把post当成单个对象来访问属性的,直接把整个数组赋值给post后,post.title.rendered自然找不到对应的属性,所以内容显示不出来。
具体修复步骤:
第一步:正确提取单个文章对象
在 axios 的 then 回调里,不要直接把json.data赋值给post,而是取数组的第一个元素:this.post = json.data[0];第二步:优化初始数据类型
把 data 里的post初始化为null或者空对象{},而不是数组,更符合实际数据类型,避免初始渲染时的报错:data () { return { post: null } }第三步:添加条件渲染(可选但推荐)
在模板里给 article 标签加上v-if="post",确保只有当 post 有数据时才渲染内容,防止页面加载时出现 undefined 的错误提示:<article v-if="post"> <h2 class="subtitle">{{ post.title.rendered }}</h2> <div v-html="post.excerpt.rendered"></div> </article>
修改后的完整代码:
<template> <div> <article v-if="post"> <h2 class="subtitle">{{ post.title.rendered }}</h2> <div v-html="post.excerpt.rendered"></div> </article> </div> </template> <script> import axios from "axios"; import Router from 'vue-router' export default { name: 'ShowPost', data () { return { post: null } }, created() { this.slug = this.$route.params.slug; }, mounted() { axios({ method: "GET", "url": "https://wpdemo.stevensoehl.com/wp-json/wp/v2/posts?slug=" + this.slug }).then(json => { this.post = json.data[0]; // 取数组第一个元素 }, error => { console.error(error); }); } } </script>
这样修改后,就能正确显示对应 slug 的文章内容啦!
内容的提问来源于stack exchange,提问作者soehlblaze
相关产品推荐
相关产品推荐

