VueJS:检索到的数据未捕获(承诺中)TypeError:刷新时数组[0]未定义

问题描述 投票:0回答:3

我正在开发用于状态管理/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] 未定义

有什么方法可以修复这些问题,甚至有建议的其他方法吗?

arrays vue.js firebase-realtime-database vuex typeerror
3个回答
1
投票

我建议您设置一个 v-if,只有在获取博客文章数据后才会解析为 true。

另一种方法是您在查看博客文章组件中检查您的 Vuex 存储中是否有博客文章,如果它们不存在,那么您可以从所述组件中获取它们。这可能不太有利,因为我认为您的整个应用程序依赖于博客文章的数据。

这里

是一个例子 我还要注意,您不必等待过滤器功能,如果您只想获取一篇博客文章,那么创建一个在 Vuex 商店中执行此操作的 getter 可能会有所帮助。


1
投票
<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"

存在且可访问。

    


0
投票

© www.soinside.com 2019 - 2024. All rights reserved.