我有一个与DatoCMS链接的NuxtJS项目。显示帖子列表,单击帖子标题等,然后转到_slug.vue页面,显示更多信息。当我单击帖子标题时,我进入_slug.vue页面,被告知“无法读取未定义的属性” title”。但是,如果刷新该页面,则可以正常工作。我可以在首页和帖子页面之间来回切换,没有任何问题,直到我查看其他帖子页面,然后问题再次发生,直到重新加载页面为止。我不知道发生了什么。
Pages目录中的index.vue:
<template>
<main>
<div v-for="(post, index) in allPosts" :key="index">
<div>
<h3>Generic Header</h3>
<p>Introduction paragraph</p>
</div>
<div>
<div>
<div
v-for="(post, index) in allPosts">
<ProductCard :post="post"/>
</div>
</div>
</div>
</div>
</main>
</template>
<script>
import ProductCard from "@/components/ProductCard";
import gql from "graphql-tag";
export default {
components: {
ProductCard
},
apollo: {
allPosts: gql`
{
allPosts {
title
text
slug
}
}
`
}
};
</script>
上面在上方调用的Components目录中的productCard.vue组件,在底部脚本标签中没有代码,只是_slug.vue文件的nuxt链接。
<nuxt-link :to="post.slug" prefetch>{{ post.title }}</nuxt-link>
_ slug.vue文件:
<template>
<div>
<h1>{{ post.title }}</h1>
<p>{{ post.text }}</p>
</div>
</template>
<script>
import gql from "graphql-tag";
export default {
apollo: {
post: {
query: gql`
query Post($slug: String!) {
post(filter: { slug: { eq: $slug } }) {
title
text
}
}
`,
prefetch({ route }) {
return {
slug: route.params.slug
};
},
variables() {
return {
slug: this.$route.params.slug
};
}
}
}
};
</script>
这是控制台的输出:
TypeError: Cannot read property 'title' of undefined
at Proxy.render (webpack-internal:///./node_modules/vue-loader/lib/loaders/templateLoader.js?!./node_modules/vue-loader/lib/index.js?!./pages/_slug.vue?vue&type=template&id=286199e1&:9)
at VueComponent.Vue._render (webpack-internal:///./node_modules/vue/dist/vue.runtime.esm.js:3542)
at VueComponent.updateComponent (webpack-internal:///./node_modules/vue/dist/vue.runtime.esm.js:4049)
at Watcher.get (webpack-internal:///./node_modules/vue/dist/vue.runtime.esm.js:4473)
at new Watcher (webpack-internal:///./node_modules/vue/dist/vue.runtime.esm.js:4462)
at mountComponent (webpack-internal:///./node_modules/vue/dist/vue.runtime.esm.js:4067)
at VueComponent.Vue.$mount (webpack-internal:///./node_modules/vue/dist/vue.runtime.esm.js:8405)
at init (webpack-internal:///./node_modules/vue/dist/vue.runtime.esm.js:3115)
at merged (webpack-internal:///./node_modules/vue/dist/vue.runtime.esm.js:3298)
at createComponent (webpack-internal:///./node_modules/vue/dist/vue.runtime.esm.js:5968)
很遗憾,我已经检查了有关“无法读取未定义的属性'title'的其他答案”,但在这种情况下,它们无济于事。
非常感谢您的帮助。 👍马特
您能否提供ProductCard.vue
组件的代码。如果script
标记中没有代码,则将无法使用template
部分中的post属性。
在script
部分中添加此代码段:
export default {
name: 'ProductCard',
props: {
post: Object
}
}