【发布时间】:2021-11-05 00:49:02
【问题描述】:
我构建了一个基于博客的页面,其中 wordpress 作为 api,nuxtjs 作为 javascript 框架。 问题发生在我的 _slug.vue 中。当我导航到单个博客(项目)帖子时,单个帖子会正常呈现。但是,如果我重新加载单个帖子页面,或者当我只输入 url 时,我会在控制台中收到错误:GET url 500 (RuntimeError)。
<template>
<div class="single-project">
<Header />
<h1>{{project.title.rendered}}</h1>
<article v-html="project.content.rendered"></article>
<ClickToAction />
</div>
<script>
/* eslint-disable */
import axios from 'axios'
export default{
data() {
return {
project: {}
}
},
async asyncData({params}){
return await axios.get('https://my-api.wp/wp-json/wp/v2/project/' + params.id)
.then((res) => {
return {
project: res.data
}
}).catch(function (error) {
if (error.response) {
// Request made and server responded
console.log(error.response.data);
console.log(error.response.status);
console.log(error.response.headers);
} else if (error.request) {
// The request was made but no response was received
console.log(error.request);
} else {
// Something happened in setting up the request that triggered an Error
console.log('Error', error.message);
}
});
}
}
</script>
以及一个项目的链接:
<nuxt-link :class="'item ' + project._embedded['wp:term'][0].map(el => el.name.toLowerCase()).join(' ')" v-for="project in projects" :key="project.id" :to="{name: 'projekte-slug', params: { slug: project.slug, id: project.id}}">
目标在 nuxt.config.js 中是静态的
编辑
经过研究发现,在 nuxt-link 参数对象中传递的 id 在重新加载后会丢失,因为它需要“父”页面来获取 id 的值。为了解决这个问题,我使用 slug 获取项目,该项目始终包含在 api 的 url project/:slug 中,并显示了所有属性(例如标题、内容......)
async asyncData({ params, $axios }) {
try {
console.log(params.slug);
const project = await $axios.$get(`https://my-api.wp/wp-json/wp/v2/project?slug=${params.slug}&_embed`)
return { project }
} catch (error) {
...
}
【问题讨论】:
标签: wordpress vue.js axios nuxt.js headless