簡體   English   中英

$fireDb 在 Nuxt Fire / Firebase Vuex 中未定義

[英]$fireDb undefined in Nuxt Fire / Firebase Vuex

我正在使用 Nuxt JS 2.9.2 來構建一個 Javascript 應用程序。 它具有通過 Nuxt Fire 模塊進行的 Firebase 集成,以及用於處理狀態管理和身份驗證的 Vuex。

我已經設置了項目,並且能夠創建用戶、登錄和注銷。

我現在正在嘗試在 Firebase 中設置一些數據以及用戶 ID,並且收到$fireDb未定義錯誤,即使用戶仍在創建中(沒有設置任何信息):

function createNewAccount (user) {
  const databaseRef = this.$fireDb.ref(`accounts/${user.uid}`)
  return databaseRef.set({
    displayName: 'Test Display Name', // use part of the email as a username
    email: 'My Test Email',
    image: 'Some Image' // supply a default profile image for all users
  })
}

export const actions = {

  /*
   * Create a user
   */
  createUser ({commit}, payload) {
    this.$fireAuth.createUserWithEmailAndPassword(payload.email, payload.password).then(function({user}) {
      commit('localStorage/setUser', { email: payload.email }, { root: true })
      createNewAccount(user)
    }).catch(function(error) {
      console.log('error registering' + error)
    });
  }
}

我想弄清楚為什么this.$fireDb是未定義的? 我試過遵循文檔,但這部分似乎壞了?

https://github.com/lupas/nuxt-fire#usage

您嘗試訪問。這店外的createNewAccount()函數。

您可以訪問商店中的 this.$fireDb、您的 .vue 文件和 nuxt 插件,但不會自動超出該范圍。

因此,您可以例如將函數移動到 store 操作中,如下所示:

export const actions = {
  /*
   * Create a user
   */
  createUser({ commit, dispatch }, payload) {
    this.$fireAuth
      .createUserWithEmailAndPassword(payload.email, payload.password)
      .then(function({ user }) {
        commit('localStorage/setUser', { email: payload.email }, { root: true })
        dispatch('createNewAccount', true) // CHANGED THIS
      })
      .catch(function(error) {
        console.log('error registering' + error)
      })
  },

  createNewAccount({ commit }, user) {
    const databaseRef = this.$fireDb.ref(`accounts/${user.uid}`)
    return databaseRef.set({
      displayName: 'Test Display Name', // use part of the email as a username
      email: 'My Test Email',
      image: 'Some Image' // supply a default profile image for all users
    })
  }
}

或者在您的應用程序中的任何其他地方運行,您可以通過 .this 訪問 nuxt 上下文。

希望有幫助:)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM