gpt4 book ai didi

javascript - Nuxt @onloadstart 不使用 beforeCreate 触发函数

转载 作者:行者123 更新时间:2023-12-04 07:34:17 24 4
gpt4 key购买 nike

Nuxt 和 SSR 的新手。我想要做的很简单:我试图在页面加载之前触发一个函数,该函数将对我的 firestore 数据进行 SSR。如果我用@onclick 添加一个按钮,它工作正常。但是当我尝试用 @onloadstart 或类似的东西替换 Button/OnClick 时,没有任何 react 。
我错过了什么?我怀疑我是从客户端的 Angular 考虑这个问题。不是 SSR 镜头。

 <template @onloadstart="beforeCreate()">
<section>
<div>
<div v-for="article in articles" id="articleCardList" :key="article">
<v-card elevation="1" outlined>
<div class="d-flex">
<v-avatar class="ma-1" size="125" tile>
<v-img :src="article.thumbnail"></v-img>
</v-avatar>
<div>
<v-card-title
class="text-h5 text-wrap d-flex justify-space-between text-caption"
v-text="article.title"
>
{{ article.title }}
</v-card-title>
</div>
</div>
</v-card>
</div>
</div>
</section>
</template>
<script>
import { fireDb } from '~/plugins/firebase.js'
export default {
data() {
return {
articles: [],
}
},

methods: {
async asyncData() {
this.articles = []

await fireDb
.collection('articles')
.get()
.then((querySnapShot) => {
querySnapShot.forEach((doc) => {
this.articles.push({
id: doc.id,
title: doc.data().title,
description: doc.data().description,
thumbnail: doc.data().thumbnail,
date: doc.data().date,
link: doc.data().link,
source: doc.data().source,
})
console.log(this.articles)
})
})
},
beforeCreate() {
window.addEventListener('beforeCreate', this.asyncData)
},
},
}
</script>

最佳答案

就让组件在页面加载之前自动获取数据而言,您已经接近可行的解决方案了。而不是 beforeCreate ,你会使用 the asyncData hook (这似乎是您的初步尝试)。
问题是你已经声明 asyncData作为组件方法,但它需要位于对象定义的顶层才能用作组件 Hook 。

export default {
// ✅ declared as a hook
asyncData() {...},

methods: {
// ❌ this should be at the top level
asyncData() {...}
},
}
请注意 asyncData只能在页面或布局组件中使用。否则,您需要切换到 the fetch hook . asyncData()无法访问 this (因为它在页面组件之前运行),所以应该删除这些引用。相反, asyncData()应该返回一个类似于从 data() 返回的数据对象。 (即, { ​articles } ):
export default {
​asyncData() {
​const articles = []

​await fireDb
​.collection('articles')
​.get()
​.then((querySnapShot) => {
​querySnapShot.forEach((doc) => {
​articles.push(/*...*/)
​})
​})

console.log(articles)
return { articles }
}
}

关于javascript - Nuxt @onloadstart 不使用 beforeCreate 触发函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67812892/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com