我正在使用基于Firebase的vue应用程序,该应用程序在成功登录后应将用户重定向到主页。单击登录后,我会收到Howewer无法在控制台中读取未定义错误的属性'$ router'。
我已经尝试过从Login组件上的“ ./router”导入路由器,但是它不起作用。
main.js
import Vue from "vue";
import firebase from "firebase";
import App from "./App.vue";
import router from "./router";
import swalPlugin from './plugins/VueSweetalert2';
Vue.config.productionTip = false;
let app ='';
firebase.initializeApp( {
apiKey: "xx",
authDomain: "xx",
databaseURL: "xx",
projectId: "xx",
storageBucket: "xx",
messagingSenderId: "xx"
});
Vue.use(swalPlugin);
firebase.auth().onAuthStateChanged(() => {
if (!app) {
app = new Vue({
router,
render: h => h(App)
}).$mount("#app");
}
});
router.js
import firebase from 'firebase';
import Vue from "vue";
import Router from "vue-router";
import Home from "./views/Home.vue";
import Login from "./views/Login.vue";
import SignUp from "./views/SignUp.vue";
Vue.use(Router);
const router = new Router({
routes: [
{
path: "*",
redirect: "/login",
},
{
path: "/",
redirect: "/login",
},
{
path: '/login',
name: 'Login',
component: Login
},
{
path: '/sign-up',
name: 'SignUp',
component: SignUp
},
{
path: "/home",
name: "Home",
component: Home,
meta: {
requiresAuth: true
}
}
]
});
router.beforeEach ((to, from, next) => {
const currentUser = firebase.auth.currentUser;
const requiresAuth = to.matched.some (record => record.meta.requiresAuth);
if (requiresAuth && !currentUser) next('login');
else if (!requiresAuth && currentUser) next('home');
else next();
});
export default router;
Login.vue
<template>
<form autocomplete="off">
<div class="login">
<h1>Login</h1>
<p>Sign in to stay updated with the latest news</p>
<hr>
<input type="text" placeholder="Email" v-model="email">
<input type="password" placeholder="Enter Password" v-model="password">
<hr>
<button @click="login">Login</button>
<p>Don't have an account yet? Create one <router-link to="/sign-up">here</router-link></p>
</div>
</form>
</template>
<script>
import firebase from 'firebase';
import Swal from 'sweetalert2';
export default {
name: 'login',
data() {
return {
email: '',
password: ''
}
},
methods: {
login: function(){
firebase.auth().signInWithEmailAndPassword(this.email, this.password).then(
function (user) {
this.$router.replace('home')
},
function (err) {
Swal.fire({
type: 'error',
title: 'An error occurred...',
text: err.message
})
}
);
}
}
}
</script>
答案 0 :(得分:0)
我认为您使用function
失去了范围。
使用es6语法(如果您可以负担/使用babel)解决问题,(user) => { .. }
。
或通过在主要登录功能中设置类似var _this = this;
的方式并对其进行引用。