Nuxt @onloadstart 不使用 beforeCreate 触发函数

Nuxt @onloadstart not triggering function using beforeCreate

Nuxt 和 SSR 的新手。我想要做的很简单:我试图在页面加载之前触发一个函数,该函数将 SSR 我的 firestore 数据。如果我用@onclick 添加一个按钮,它工作正常。但是当我尝试用 @onloadstart 或类似的东西替换 Button/OnClick 时,没有任何反应。

我错过了什么?我怀疑我是从客户端的角度考虑这个问题的。不是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>

就让组件在页面加载之前自动获取数据而言,您已经接近于一个可行的解决方案。您将使用 the asyncData hook 而不是 beforeCreate(这似乎是您的初步尝试)。

问题是您已将 asyncData 声明为 组件方法 ,但它需要位于对象定义的顶层才能使用作为组件挂钩。

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

  methods: {
    // ❌ this should be at the top level
    asyncData() {...} 
  },
}

请注意 asyncData 只能在页面或布局组件中使用。否则,您需要切换到 the fetch hook.

asyncData() 无法访问 this(因为它在页面组件之前是 运行),因此应删除这些引用。相反,asyncData() 应该 return 一个类似于从 data() 编辑的 return 的数据对象(即 { ​articles }):

export default {
  ​asyncData() {
    ​const articles = []

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

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