这个。$ firebase是未定义的

时间:2018-04-25 23:10:44

标签: firebase vue.js firebase-authentication

我正在构建我的第一个Vue.js应用,尝试将case class Selector[T](condition: T => Boolean) { def unapply(seq: Seq[T]): Option[T] = seq.find(condition) } object Selector { // seq argument is used only to infer type `T` def from[T](seq: Seq[T])(condition: T => Boolean): Selector[T] = Selector(condition) } def process(seq: Seq[SomeObjectType]): SomeReturnType = { // Create an extractor object instance val Select = Selector.from(seq)(_.somePropertyTest) seq match { case Seq() => // seq empty case Select(o) => // found o, we can process it now case _ => // didn't find a suitable element } } vuex一起使用。

vuexfire

//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');

这符合OK,但会在控制台中抛出//store/mutations.js export default { SET_USER(state) { state.user = this.$firebase.auth().currentUser; }, ... }

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

2 个答案:

答案 0 :(得分:3)

当你这样做时:

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

您将$firebase添加到Vue实例。

this.$firebase

要工作,this应该是Vue的提示。换句话说,该行必须在Vue方法/ hook / computed / etc中执行 inside

您展示的代码不会这样做:

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

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

因此,要在Vue实例之外工作,必须

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

如果上面的行在之后执行(按时间/顺序),则初始化$firebase的行。

答案 1 :(得分:0)

我想我解决了这个问题:

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