此.$firebase未定义
我正在构建我的第一个Vue.js应用程序,尝试将此.$firebase未定义,firebase,vue.js,firebase-authentication,Firebase,Vue.js,Firebase Authentication,我正在构建我的第一个Vue.js应用程序,尝试将vuex与vuexfire一起使用 //main.js import firebase from 'firebase'; ... Vue.prototype.$firebase = firebase.initializeApp(config); ... firebase.auth().onAuthStateChanged(() => { /* eslint-disable no-new */ new Vue({ el:
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();
}
});
以及:
以及:
这符合OK,但在控制台中抛出TypeError:This.$firebase未定义[了解更多信息]
知道我做错了什么吗?我想我已经阅读了所有相关教程和StackOverflow问题,并尝试了所有方法。当您这样做时:
Vue.prototype.$firebase=firebase.initializeApp(配置);
将$firebase
添加到Vue实例。所以
this.$firebase
要工作,此
应为Vue指令。换句话说,该行必须在Vue方法/hook/computed/etc内部执行
而您显示的代码并不能做到这一点:
const db=this.$firebase.firestore();
在上面的代码中,this
是外部上下文。(可能是窗口
)
因此,要使其在Vue实例之外工作,您必须执行以下操作:
const db=Vue.prototype.$firebase.firestore();
如果上面的行在初始化
$firebase的行之后执行(按时间/顺序),我想我解决了这个问题:
将firebase初始化移动到store.js
更改firebase.auth().onAuthStateChanged(()=>{
为Vue.prototype.firebase.auth().onAuthStateChanged(()=>{
在main.js中
导入firebase为:从'@firebase/app'导入firebase;
导入“@firebase/firestore”;
[了解更多信息]
discover?这只是undefined
Ah上的常规Mozilla文档,没有太大帮助。这只是将错误更改为TypeError:\uuu网页包\u导入的\u模块\u 1\u vue\ue。默认。原型。$firebase是未定义的
我认为核心问题是firebase在store.js和组件中调用时没有初始化。我想不出来t如何等待。如何首先初始化firebase,然后才运行routes.js和其他所有程序?将Vue.prototype.$firebase=firebase.initializeApp(config);
行放置为“接近顶部”尽可能在您的main.js
文件中执行,因此它会先执行。您可以展开问题中的main.js
代码吗?显示导入store.js
的位置。还可以展开store.js
,显示定义和导出store
的位置。
//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;
},
...
}