【问题标题】:this.$firebase is undefinedthis.$firebase 未定义
【发布时间】:2018-10-06 12:56:01
【问题描述】:

我正在构建我的第一个 Vue.js 应用程序,尝试使用 vuexvuexfire

//main.js
import firebase from 'firebase';

...

Vue.prototype.$firebase = firebase.initializeApp(config);

...

firebase.auth().onAuthStateChanged(() => {
  /* eslint-disable no-new */
  new Vue({
    el: '#app',
    store,
    router,
    render: h => h(App),
    created() {
      this.$store.dispatch('setDealsRef');
    },
  });
});

router.beforeEach((to, from, next) => {
  const currentUser = firebase.auth().currentUser;
  const requiresAuth = to.matched.some(record => record.meta.requiresAuth);
  if (requiresAuth && !currentUser) {
    next('/signin');
  } else if (requiresAuth && currentUser) {
    next();
  } else {
    next();
  }
});

还有:

//store/index.js
import Vue from 'vue';
import Vue from 'vue';
import Vuex from 'vuex';
import { firebaseMutations } from 'vuexfire';

...

Vue.use(Vuex);

const db = this.$firebase.firestore();
const dealsRef = db.collection('deals');

还有:

//store/mutations.js
export default {
  SET_USER(state) {
    state.user = this.$firebase.auth().currentUser;
  },
...
}

这符合 OK,但在控制台中抛出 TypeError: this.$firebase is undefined[Learn More]

知道我做错了什么吗?我想我已经阅读了所有相关教程和 StackOverflow 问题,并且尝试了所有方法。

【问题讨论】:

  • [Learn More] 透露了什么?
  • 这只是 undefined 上的常规 Mozilla 文档
  • 啊,帮不上什么忙。

标签: firebase vue.js firebase-authentication


【解决方案1】:

当你这样做时:

Vue.prototype.$firebase = firebase.initializeApp(config);

您将 $firebase 添加到 Vue 实例。所以对于

this.$firebase

为了工作,this 应该是一个 Vue 实例。换句话说,该行必须 Vue 方法/hook/computed/etc 中执行。

而您显示的代码并没有这样做:

const db = this.$firebase.firestore();

在上面的代码中,this 是外部上下文。 (可能是window。)

因此,要使其在 Vue 实例之外工作,您必须这样做

const db = Vue.prototype.$firebase.firestore();

假设上面的行(按时间/顺序)您初始化$firebase 的行之后执行。

【讨论】:

  • 这只是将错误更改为TypeError: __WEBPACK_IMPORTED_MODULE_1_vue__.default.prototype.$firebase is undefined
  • 我认为核心问题是在 store.js 和组件中调用 firebase 时没有初始化它。我不知道如何等待它。
  • 我怎样才能先初始化firebase,然后然后运行routes.js和其他一切?
  • Vue.prototype.$firebase = firebase.initializeApp(config); 行放在main.js 文件中尽可能“靠近顶部”的位置,以便它在其他任何内容之前执行。
  • 您能否在问题中扩展您的main.js 代码?显示store.js 的导入位置。同时展开您的store.js,显示store 的定义和导出位置。
【解决方案2】:

我想我解决了这个问题:

  1. 将 firebase 初始化移至 store.js
  2. 在 main.js 中将 firebase.auth().onAuthStateChanged(() => { 更改为 Vue.prototype.firebase.auth().onAuthStateChanged(() => {
  3. 将 Firebase 导入为:import firebase from '@firebase/app'; import '@firebase/firestore';

【讨论】:

    猜你喜欢
    • 2016-08-21
    • 2020-01-21
    • 2018-04-09
    • 2016-01-27
    • 2019-12-29
    • 2021-06-08
    • 2020-07-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多