我正在将一些产品类别数据从Prismic加载到我的Nuxt项目中,我正在寻找关于最佳实践的一些澄清。具体地说,如何处理仍在获取数据的状态,并且侧边栏中没有要显示的内容。
现在,这是我正在做的事情:
我有一个侧边栏组件(Sidebar.vue):
<template>
<div class="xl:flex-shrink-0 xl:w-64 border-r border-gray-200 pt-5 pb-4 bg-white overflow-y-auto ">
<h3 class="text-xl font-bold text-gray-800">{{ navigation.heading }}</h3>
<div class="mt-5 flex-grow flex flex-col">
<nav class="flex-1 px-2 space-y-1 bg-white" aria-label="Sidebar">
<div v-for="(category, index) in navigation.categories" :key="index">
<SidebarItem v-if="!category.subcategories.length" :category="category"/>
<SidebarSection v-else-if="category.subcategories.length" @click="toggleExpansion(index)" :category="category"/>
</div>
</nav>
</div>
</div>
</template>
<script lang="ts">
export default {
data() {
return {
navigation: new Navigation('Categories')
}
},
async mounted() {
const that = this
this.fetchCategories()
.then(function() {
that.navigation = that.$store.getters.navigation
})
},
methods: {
...mapActions({ fetchCategories: 'fetchCategories' })
}
}
</script>如您所见,我有一个navigation属性,它将包含填充侧边栏所需的所有数据。目前,我已经初始化了一个占位符实例(new Navigation('Categories')),因为没有这个,Vue报告navigation是未定义的。
这并不是一种理想的解决方案。在不提供占位符实例的情况下,在加载数据之前处理这种中间状态最合适的方法是什么?
发布于 2020-12-29 07:32:10
Nuxt的fetch hook在这里可能很有用。它公开$fetchState (包括pending、error和timestamp)以强制使用或在模板中使用。您的模板可以在呈现navigation数据之前检查pending标志:
<template>
<div v-if="!$fetchState.pending" ?
class="xl:flex-shrink-0 xl:w-64 border-r border-gray-200 pt-5 pb-4 bg-white overflow-y-auto">
<h3 class="text-xl font-bold text-gray-800">{{ navigation.heading }}</h3>
<div class="mt-5 flex-grow flex flex-col">
<nav class="flex-1 px-2 space-y-1 bg-white" aria-label="Sidebar">
<div v-for="(category, index) in navigation.categories" :key="index">
<SidebarItem v-if="!category.subcategories.length" :category="category"/>
<SidebarSection v-else-if="category.subcategories.length" @click="toggleExpansion(index)" :category="category"/>
</div>
</nav>
</div>
</div>
</template>
<script lang="ts">
export default {
// BEFORE:
// async mounted() {
// const that = this
// this.fetchCategories()
// .then(function() {
// that.navigation = that.$store.getters.navigation
// })
// },
// AFTER:
async fetch() {
await this.fetchCategories()
this.navigation = this.$store.getters.navigation
},
}
</script>https://stackoverflow.com/questions/65482885
复制相似问题