1

我正在使用 Nuxt 构建一个网络应用程序,并且很难尝试从 Firestore 中的消息集合中获取一条随机消息。

我尝试使用一种方法来返回随机消息以及随机化messages对象中数组的索引值。

为了更好地解释,这就是我的 Messages.vue 组件的当前脚本标记的样子:

<script>
import {db} from '../plugins/firebase'
    export default {
        firestore() {
            return {
                messages: db.collection("messages")
            }
        },
        data: function() {
            return {
                messages: ''
            }
        },
        methods: {
            randomMessage() {
                var randomMessage = this.messages[Math.floor(Math.random()*this.messages.length)];
                return randomMessage
            }
        }

    }
</script>

randomMessage()方法确实从集合中返回了一个随机消息对象,但它是整个对象,我只.text想要message. 换句话说,{{messages[Math.floor(Math.random()*this.messages.length)]}}可以从 Firestore 返回一个随机消息文档,但是当我使用 时{{messages[Math.floor(Math.random()*this.messages.length)].text,我收到一个错误:

Cannot read property 'text' of undefined

我也尝试在此线程中遵循 Dan McGrath 的回答但没有成功:

Firestore:如何在集合中获取随机文档

我不确定如何在我的 Nuxt 项目中实施 Wrap-around 解决方案。当我尝试将该解决方案用作我的脚本导出中的一种方法时,我得到一个语法错误。

完整的 repo 可以在这里找到:https ://github.com/SIeep/motivation-app

任何帮助或指导表示赞赏!

4

0 回答 0