我正在开发用于状态管理/firebase 职位项目的
vuejs
/(vuex)
。
因此,我有一个帖子的 firestore 集合(具有名称 id 所有者内容和创建时间戳的对象数组...),当用户想要访问单个帖子时,它会将他重定向到单个帖子的路径(. .../view-post/postid).
所有帖子都是使用 getDocs 方法从 firestore 检索的,并将其存储在 blogPosts 变量中...
我正在使用一个数据,它是一个数组,当安装的生命周期钩子开始调用时(安装组件时),我使用该数组并通过过滤所有帖子到帖子ID,然后开始填充组件上的数据像这样使用数组[0]:
currentBlog: null
我的 html 标记(模板):
async mounted() {
this.currentBlog = await this.blogPosts.filter((post) => {
return post.blogID == this.$route.params.blogid;
});
}
我使用第一个条件只是为了确保帖子在完成过滤后出现,但是......
现在我收到了帖子,我面临的问题是当我从帖子刷新页面时,有时当我直接打开帖子时,我会收到此错误:
未捕获(承诺中)类型错误:this.currentBlog[0] 未定义
有什么方法可以修复这些问题,甚至有建议的其他方法吗?
<section class="preview" v-if="currentBlog">
<h2>{{ currentBlog[0].blogTitle }}</h2>
<p>Posted on: <span>{{ dateFormat() }}</span> <span v-if="currentBlog[0].editTime">(Last edit:
{{ editFormat() }})</span></p>
<img class="blogCover" :src="currentBlog[0].blogCoverFileURL" :alt="currentBlog[0].blogCoverPhoto">
<div class="html-blog" v-html="currentBlog[0].blogHTML"></div>
<hr />
<div class="tags">
<h4>Tags:</h4>
<div class="tag" v-for="(tag,index) in currentBlog[0].blogTags" @click="filterPosts(tag)" :key="index">
{{ tag }}
</div>
</div>
<hr />
</section>
条件。
你的 v-if 应该是;v-if
这将确保 v-if="currentBlog && currentBlog.length"
存在且可访问。