如何使我的数据对象具有高度的反应性?

时间:2019-10-15 08:08:51

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

我正在创建一个带有类别,主题和帖子的论坛应用。每个线程都附加有一个user_id,我使用firebase检索用户。然后,使用给定的文档更新this.thread.user。但是user属性不是反应性的。我附加了一个观察程序来尝试解决问题,但是没有成功。我的代码如下:

<template>
    <div class="container">
        <h1 class="display-3" v-if="thread">Thread: {{ thread.title }}</h1>
        <small v-if="thread && thread.user">Created by <span class="font-weight-bold">{{ thread.user.displayName }}</span></small> // doesnt work
        <hr>
        <div class="alert alert-success" v-if="thread">
            {{ thread.body }}
        </div>

        <div v-for="(post, index) in posts"
             :key="index"
             class="alert alert-secondary">
            {{ post.body }}
        </div>
    </div>
</template>

<script>
    import db from '../firebase/init';
    export default {
        name: "Thread",
        props: ['app'],
        data() {
            return {
                thread: null,
                posts: [],
                user: null
            }
        },
        mounted() {
            this.getThread();
        },
        watch: {
            thread: {
                deep: true,
                handler(data) {
                    this.thread.user = data.user;
                }
            }
        },
        methods: {
            getThread() {
                db.collection('threads').doc(this.$route.params.id).get().then(doc => {
                    if (!doc.exists) {
                        this.$router.push('/');
                        return;
                    }
                    this.thread = {id: doc.id, ...doc.data()};
                    const ref = db.collection('profiles');
                    ref.where('user_id', '==', this.thread.user_id).get().then(snapshot => {
                        snapshot.forEach(doc => {
                            this.thread.user = {
                                id: doc.id,
                                ...doc.data()
                            } //doesnt work
                        })
                    })
                })
            },
            getPosts() {
                const ref = db.collection('posts');
                ref.where('thread_id', '==', this.thread.id).get().then(snapshot => {
                    snapshot.forEach(doc => {
                        this.posts.push({id: doc.id, ...doc.data()});
                    })
                })
            }
        }
    }
</script>

0 个答案:

没有答案