【问题标题】:How can I get the firebase's output to the html's template on page load?如何在页面加载时将 firebase 输出到 html 模板?
【发布时间】:2021-10-20 09:14:10
【问题描述】:

我正在使用 VueJs 为博客创建帖子页面。

我有这个作为模板:

<template>
...
            <q-item-section>
              <q-item-label class="text-subtitle1">
                <strong>Danny Connell</strong>
                <span class="text-grey-7">
                  @danny__connell 
                </span>
              </q-item-label>
              <q-item-label class="qweet-content text-body1">{{ get_post().content }}</q-item-label>
            </q-item-section>
...
</template>

我正在尝试将帖子的内容、vue 的方法(查询 firebase)获取到模板中。

export default {
  name: 'PagePost',
  methods: {

    get_post(){
        var post_id = this.$route.query.id
        var post = {
            id: post_id,
        }
        post.content = "hi"
        db.collection('posts').doc(post_id).get().then(snapshot => {
            const document = snapshot.data()
            post.content = document.content //lets say the content is "hello"
        return post
    },
}

我在模板"hi" 中看到,但不是数据库中的内容(“hello”),当我删除post.content = "hi" 行时,我在html 的模板中看不到任何内容。

据我了解,数据库检索数据库内容需要时间,因此在完成数据库查询之前会跳到下一行。

我尝试使用 async/await,但我仍然没有得到帖子的内容:

export default {
  name: 'PagePost',
  methods: {

    async get_post(){
        var post_id = this.$route.query.id
        var post = {
            id: post_id,
        }
        await db.collection('posts').doc(post_id).get().then(snapshot => {
            const document = snapshot.data()
            post.content = document.content //lets say the content is "hello"
        return post
    },
}

如何将 db 的输出获取到 html 的模板中?

【问题讨论】:

    标签: vue.js vuejs2 async-await vue-component


    【解决方案1】:

    当您在这里拨打get_post()

    <q-item-label>{{ get_post().content }}</q-item-label>
    

    您没有呈现反应性属性,请尝试在data 中定义postContent,并在组件挂载时调用get_post()

    示例:

    <template>
      <QItemLabel class="qweet-content text-body1">{{ postContent }}</QItemLabel>
    </template>
    
    <script>
    export default {
      name: 'PagePost',
      data: () => ({
        postContent: ''
      }),
      mounted() {
        this.get_post()
      },
      methods: {
        get_post() {
          const post_id = this.$route.query.id
          const post = { id: post_id } // Not using this, check this line!
    
          db.collection('posts')
            .doc(post_id)
            .get()
            .then(snapshot => {
              this.postContent = snapshot.data().content
            })
        }
      }
    }
    </script>
    

    【讨论】:

      猜你喜欢
      • 2016-04-04
      • 1970-01-01
      • 2019-07-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-18
      • 2020-09-09
      相关资源
      最近更新 更多