【问题标题】:Trying to return a random post with Vue 3 composition API and Firebase尝试使用 Vue 3 组合 API 和 Firebase 返回随机帖子
【发布时间】:2025-12-07 15:35:02
【问题描述】:

试图将我的头脑围绕在组合 api 上,但显然需要一些帮助。 使用这个从 Firebase 数据库加载我所有的“报价”

import { ref } from 'vue'
import { projectFirestore } from '../firebase/config'

const getQuotes = () => {
  const quotes = ref([])
  const error = ref(null)

  const load = async () => {
    try {
      const res = await projectFirestore.collection('quotes').get()
      
      quotes.value = res.docs.map(doc => {
        return { ...doc.data(), id: doc.id }
      })
    }
    catch (err) {
      error.value = err.message
      console.log(error.value)
    }
  }

  return { quotes, error, load}
}

export default getQuotes

按预期工作。 但后来我尝试创建一个过滤器,所以只有 1 引用像这样随机显示:

<template>
  <section class="home">
    <h1 style="color: pink">{{ randomQuote }}</h1>
    <Quote :quote="quote" v-for="quote in quotes" :key="quote.id" />
  </section>
</template>

<script>
import getQuotes from '@/composables/getQuotes'
import Quote from '@/components/Quote.vue'
import { computed } from '@vue/reactivity'

export default {
  name: 'Home',
  components: { Quote },
  setup() {
    const { quotes, error, load } = getQuotes()
    const randomQuote = computed(() => {
      return quotes.Math.floor(Math.random() * quotes.length)
    })

    load()

    return { randomQuote, quotes, error }
  }
}
</script>

在我的脑海中,这应该可以工作...任何可以发现错误并提醒我的人?

【问题讨论】:

  • quotes.Math.floor
  • @EstusFlask 是什么意思?
  • 您询问了错误,就是这样。 quotes.Math 表示您尝试访问引号数组上名为 Math 的属性,该属性不存在。如果您的意图是计算数组索引,那么这是错误的语法。
  • 感谢@EstusFlask
  • @EstusFlask 您能否在解决方案中添加您的评论作为答案,使其更加可见并帮助社区找到它?谢谢。

标签: javascript firebase vue.js google-cloud-firestore


【解决方案1】:

此语法意味着quotes.Math.floor(Math.random() * quotes.length)quotes 数组上名为Math 的属性,而应该访问的是Math 全局变量。由于数组没有这样的属性,这将导致错误。如果目的是指定动态数组索引,则与访问属性没有区别。

为了访问索引,应该使用括号表示法,可能:

quotes[Math.floor(Math.random() * quotes.length)]

【讨论】: