【发布时间】:2020-12-21 19:16:39
【问题描述】:
我正在使用 WordPress API 为后端和 nuxt.js 为前端构建一个网站。 尽管我不断收到“无法读取未定义的属性'标题'”,但我在前端显示数据时遇到问题
下面是我的 store/index.js
import axios from 'axios'
export const state = () => ({
posts: [],
pages: [],
})
export const mutations = {
SET_POSTS: (state, posts) => {
state.posts = posts
},
SET_PAGES: (state, pages) => {
state.pages = pages
},
}
export const actions = {
async getPages({ state, commit }) {
if (state.pages.length) return
try {
let pages = await axios.get(`https://domain.dev/wp-json/wp/v2/pages`).then((res) => res.data)
pages = pages.map(({ id, slug, title, content, acf }) => ({ id, slug, title, content, acf }))
commit('SET_PAGES', pages)
} catch (err) {
console.error('getPages', err)
}
},
async getPosts({ state, commit }) {
if (state.posts.length) return
try {
let posts = await axios.get(`https://domain.dev/wp-json/wp/v2/posts?page=1&per_page=100&_embed=1`).then((res) => res.data)
posts = posts.map(({ id, slug, title, content, excerpt, acf }) => ({ id, slug, title, content, excerpt, acf }))
commit('SET_POSTS', posts)
} catch (err) {
console.error('getPosts', err)
}
}
}
我的 About.vue 视图模板是这样的
<template>
<div>
<h1>{{ about.title.rendered }}</h1>
</div>
</template>
<script>
import { mapState, mapActions } from 'vuex'
export default {
name: 'About',
computed: {
...mapState(['pages']),
about() {
return this.pages.find(
(page) => page.slug === 'about'
)
},
},
created() {
this.getPages()
},
methods: {
...mapActions(['getPages'])
},
}
</script>
<style lang="scss" scoped>
</style>
我在这里更改了 API URL,但它确实显示了可以在此处看到的数据
{
"id": 17,
"date": "2020-12-18T11:36:21",
"date_gmt": "2020-12-18T11:36:21",
"guid": {
"rendered": "https://domain.dev/?page_id=17"
},
"modified": "2020-12-18T11:36:42",
"modified_gmt": "2020-12-18T11:36:42",
"slug": "about",
"status": "publish",
"type": "page",
"link": "https://domain.dev/about/",
"title": {
"rendered": "About"
},
"content": {
"rendered": "<p>Nothing much to say!</p>\n",
"protected": false
},
"excerpt": {
"rendered": "<p>Nothing much to say!</p>\n",
"protected": false
},
"author": 1,
"featured_media": 0,
"parent": 0,
"menu_order": 20,
"comment_status": "closed",
"ping_status": "closed",
"template": "",
"meta": [],
"acf": [],
【问题讨论】:
-
您的模板中有
about.title.rendered,而about是undefined会导致该错误。 -
@ChrisG 我知道 about 没有被定义我只是不明白我是如何定义它的?
-
@ChrisG 也刚刚注意到,如果我转到我的主页“/”然后导航回关于“/about”页面标题确实会加载它只有当我刷新页面时我才会收到“未定义”错误
-
我遇到了类似的问题,在 axios 响应中它是
.data下的所有内容。你试过登录data.title吗? -
这些请求是异步的,但是您的模板还没有准备好
pages为空并且about()因此还没有找到任何东西。试试{{ about && about.title.rendered }}
标签: javascript wordpress vue.js nuxt.js wp-api