【问题标题】:vue router unexpected redirectionvue路由器意外重定向
【发布时间】:2017-07-21 12:16:24
【问题描述】:

这是我的路由代码:

// export so we can use in components
export var router = new VueRouter();

// define routes
router.map({
    'home': {
        component: Home,
        auth: true
    },
    'login': {
        component: Login,
        auth: false
    }
});

// fallback route
router.redirect({
    '*': 'home'
});

router.beforeEach(function (transition) {
    console.log("here!");
    console.log("beforeeach auth.user.authenticated: "+auth.user.authenticated)
    if (transition.to.auth && !auth.user.authenticated) {
        // if route requres authentication i.e. auth:true in routes
        // and isn't authenticated
        transition.redirect('login');
    } else {
        transition.next();
    }
});
// expose the whole thing on element with 'app' as an id
router.start(App, '#app');

这是我的auth/index.js

export default {
    user: {
        authenticated: false
    },

    login: function(context, creds, redirect) {
        this.user.authenticated=true;
        console.log("logged in!");
        router.go('/home');
    },

    logout: function() {
        this.user.authenticated=false;
        console.log("logout");
        router.go('/login');
    }
}

我的 Nav.vue:

<template>
    <div class="top-nav-bar" v-if="user.authenticated">
     // other code here....
                   <ul class="notification user-drop-down">
                    <li><a href="#" @click="logout()">Logout</a></li>
                   </ul>
     // other code here ...
    </div>
</template>

<script>
    import auth from '../services/auth';

    export default {
        data: function () {
            return {
                user: auth.user
            }
        },
        methods: {
            logout: function () {
                auth.logout();
            }
        }
    }
</script>

当我点击注销按钮时,它会重定向到localhost:8080/#!/home 但我的 auth.logout()router.go('/login') 。所以它应该重定向到登录控制器!

当我手动输入浏览器 localhost:8080/!#/home 时,它会正确重定向到 /login 页面。那么为什么注销按钮停留在 /home (我看到一个空白页面并且没有控制台错误!)?

编辑:

我正在使用 vue 1.0.7 和 vue-router 0.7.5

【问题讨论】:

    标签: javascript vue.js vue-component vue-router


    【解决方案1】:

    你的问题是

    router.go
    

    go 方法接受一个整数作为参数(参见http://router.vuejs.org/en/essentials/navigation.html

    我想你真的想要一个

    router.push({ path: "/login"})
    

    【讨论】:

    • 我正在使用 vue 1 和 vue 路由器 0.7.5。刚刚更新了我的问题
    【解决方案2】:

    我收到此错误是因为我使用了&lt;a&gt; 标签。

    &lt;li&gt;&lt;a href="#" @click="logout()"&gt;Logout&lt;/a&gt;&lt;/li&gt;

    所以它会转到# url(导致回退路由)而不是调用@click。 因此我不得不使用@click.prevent 来防止锚标签的这种默认行为:

    &lt;li&gt;&lt;a href="#" @click.prevent="logout()"&gt;Logout&lt;/a&gt;&lt;/li&gt;

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-04-09
      • 2020-12-18
      • 2018-04-13
      • 1970-01-01
      • 2019-06-28
      • 2021-10-20
      • 2021-12-17
      • 2019-06-11
      相关资源
      最近更新 更多