导航gaurd无法正常工作

时间:2017-03-18 11:42:40

标签: vue.js vuejs2 vue-router vuex

我将用户的状态存储在store.js中(使用vuex进行状态管理) 当用户登录时,登录状态在store.js中设置为true

我检查用户是否已登录并使用 v-if 我隐藏登录按钮。直到他一切正常

现在为了检查目的,我删除了登录按钮上的 v-if 条件 我在!ogin.vue 组件中输入导航防护之前设置了á,如下所示

login.vue

beforeRouteEnter(to, from, next){
         next(vm => {
            if(vm.$store.getters.g_loginStatus === true){
                next('/');
            }else{
                next(); 
            }
         })
    }

如果用户已登录并按下登录按钮,则会将其重定向到主页

在设置导航防护装置时,此功能正常。

但是当我在搜索中直接输入登录组件网址(localhost:8080 / login)时出现问题

登录组件正常加载而不会被重定向到主页...

为什么会这样?我做错了什么

我在route meta fields

的文档后面尝试了使用路径元字段的另一种方法

但同样的问题 当我在搜索中键入直接网址到登录组件时未被重定向

import Vue from 'vue'
import Vuex from 'vuex'
import * as firebase from 'firebase'

Vue.use(Vuex);

export const store = new Vuex.Store({

state: {
loggedIn: false,
userName: 'Guest',
error: {
    is: false,
    errorMessage: ''
},
toast: {
    is: false,
    toastMessage: ''
}
},

getters: {
g_loginStatus: state => {
    return state.loggedIn;
},
g_userName: state => {
    return state.userName;
},
g_error: state => {
    return state.error;
},
g_toast: (state) => {
    return state.toast;
}
},
mutations: {
m_logInUser: (state) => {
    state.loggedIn = true;
},
m_loggedOut: (state) => {
    state.loggedIn = false;
}
},
actions: {
a_logInUser: ({state, dispatch}, user) => {
    return new Promise((resolve, reject) => {
        firebase.auth().signInWithEmailAndPassword(user.e, user.p).then(
            () =>{
                resolve(dispatch('a_authStateObserver'));   
            }, error => {
                state.error.is = true;
                let errorCode = error.code;
                let errorMessage = error.message;
                if (errorCode === 'auth/wrong-password') {
                    state.error.errorMessage = 'Wrong password.';
                } else {
                    state.errorMessage = errorMessage;
                }
            }
        );
    });

},
a_loggedOut: () => {
    firebase.auth().signOut().then(() => {
        dispatch('a_authStateObserver');    
    });
},
a_signUpUser: ({state, dispatch}, user) => {
    return new Promise((resolve, reject) => {
        firebase.auth().createUserWithEmailAndPassword(user.e, user.p).then(
            (u) =>{
                let uid = u.uid;
                resolve(dispatch('a_authStateObserver'));   
            }, error => {
                state.error.is = true;
                let errorCode = error.code;
                let errorMessage = error.message;
                if (errorCode === 'auth/wrong-password') {
                    state.error.errorMessage = 'Wrong password.';
                } else {
                    state.errorMessage = errorMessage;
                }
            }
        );
    });

},
a_authStateObserver: ({commit, state}) => {
    firebase.auth().onAuthStateChanged(function(user) {

        if (user) {
            // User is signed in.
            var displayName = user.displayName;
            state.userName = user.email;
            state.error.is = false;
            commit('m_logInUser');
        } else {
            // User is signed out.
            commit('m_loggedOut');
        }
    });
}

}     });

login.vue

<template>
    <div class="container">
<div class="row">
    <div class="form_bg center-block">
        <form @submit.prevent="loginUser">
             <h3 class="text-center">Log in</h3>
            <br/>
            <div class="form-group">
                <input v-model="email" type="email" class="form-control" placeholder="Your Email">
            </div>
            <div class="form-group">
                <input v-model="password" type="password" class="form-control" placeholder="Password">  
                </div>
               <div class="align-center">
               <p class="error" v-if="g_error.is">{{ g_error.errorMessage }}</p>
               <button type="submit" class="btn btn-success center-block">Log in</button>
             </div>
        </form>
        <br>
        <p style="display:inline-block">Don't have an account?</p>
        <router-link to="/signup" tag="a" style="display:inline-block">Sign up</router-link>
    </div>
</div>
</div>
</template>

<script>
  import { mapGetters } from 'vuex'
export default{
    data(){
        return{
            email: '',
            password: ''
        };
    },
    methods: {
        loginUser(){
            this.$store.dispatch('a_logInUser', {e: this.email, p: this.password}).then(() =>{
                this.$router.replace('/statuses');

            });
        }
    },
    computed: {
        ...mapGetters([
            'g_error'
        ])
    },
    beforeRouteEnter(to, from, next){
         next(vm => {
         console.log(vm.$store.getters.g_loginStatus);
            if(vm.$store.getters.g_loginStatus === true){
                next('/');
            }else{
                next(); 
            }
         })
    }
}

**routs.js**

import Home from './components/Home.vue'
import Users from './components/user/Users.vue'
import Statuses from './components/user/Statuses.vue'
import Post from './components/Post.vue'
import UserStatus from './components/user/UserStatus.vue'
import Signup from './components/auth/Signup.vue'
import Login from './components/auth/Login.vue'

export const routes = [
{path: '/', component: Home, name:'home'},
{path: '/users', component: Users, name:'users'},
{path: '/statuses', component: Statuses, name:'statuses'},
{path: '/current', component: UserStatus, name:'currentUser'},
{path: '/signup', component: Signup, name:'signup'},
{path: '/login', component: Login, name:'login'},
{path: '/post', component: Post}

];

0 个答案:

没有答案