如何在 NUXT js 中访问 firebase realtimedb

How to access firebase realtimedb in NUXT js

我们在 firebase 中有一个 realtimedb,其数据如下:

在我们的nuxt页面上有如下方法:

async getDb () {
      const messageRef = this.$firebase.database.ref('test')
      try {
        const snapshot = await messageRef.once('value')
        alert(snapshot.val().message)
      } catch (e) {
        alert(e)
      }
    },

也就是运行这样装进去的:

mounted () {
    this.getDb()
  },

我不断收到此错误:

Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'database')

我是不是做错了什么?我在 Nuxt.config.js 中拥有所有 firebase 配置,suth 工作正常。我还将 realtimedb 添加到服务中:

 services: {
  realtimeDb: true,
  auth: {
    ssr: true,
    // it is recommended to configure either a mutation or action but you can set both
    initialize: {
      onAuthStateChangedMutation: 'ON_AUTH_STATE_CHANGED_MUTATION'
      // onAuthStateChangedAction: 'onAuthStateChangedAction'
    }
  },

您实际上如何从 realtimedb 访问数据,以便我可以在我的页面上显示测试数组?

您使用的 $firebase 未包含在此 documentation 中。要授予对实时数据库的访问权限,请使用以下命令:

$fire.database

$fireModule.database

注:

If you are using nuxt/firebase version 6 use realtimeDb and database for version 7 in services of nuxt.config.js, see this link for more details.