问题描述
我正在构建一个网站,后端使用 wordpress API,前端使用 nuxt.js。 我在前端显示数据时遇到问题,尽管我一直收到“无法读取未定义的属性‘标题’”
下面是我的商店/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,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,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","author": 1,"featured_media": 0,"parent": 0,"menu_order": 20,"comment_status": "closed","ping_status": "closed","template": "","Meta": [],"acf": [],
解决方法
当 computed
或 about
为假时,使用默认为空字符串的 about.title
:
<template>
<div>
<h1>{{ title }}</h1>
</div>
</template>
computed: {
title() {
return this.about?.title?.rendered || ''
}
}
您必须在这里使用计算,因为出于某种原因,Vue 目前似乎不支持 <template>
中的 optional chaining,但它在组件中使用时可以正确转译。
显然,当组件没有 ''
或 about
(即:about.title
、'--'
、等)。
输入“关于”插入“{{ about.title.rendered }}”