vue.js - vuejs beforeRouteEnter。如果用户已登录,则禁用转到 url

标签 vue.js authentication vue-router vue-resource

如果用户已登录,我想禁用转到 url“登录”。我不使用 vuex。我从方法“beforeRouteEnter”发送ajax(检查登录并获取页面上的数据),但在此之前,我转到路由(我可以看到html组件登录页面和url“/login”)并从此页面重定向后。

我根本没有访问指定的 URL,该怎么办?

    beforeRouteEnter: (to, from, next) => {
        next(function (vm) {
            vm.$http.get('http://cake.vue.loc/api/checkLogin')
                .then(response => {
                    return response.json()
                })
                .then(response_data => {
                    if (response_data.status == 'success') {
                        vm.$router.push("/");
                    }
                });
        });
    }

最佳答案

您可能需要查看 router.beforeEach 而不是 beforeRouteEnter。事实上,正如文档所指定的那样:在确认渲染此组件的路由之前调用 beforeRouteEnter

以下是使用 beforeEach 执行此操作的方法:

const router = new VueRouter({ ... })

router.beforeEach((to, from, next) => {
  let userIsLogged = // Call to your api
  if (to.name === "login" && userIsLogged) {
    // Redirect user to homepage
    return next({path: '/'})
  }
  // Let the user pass
  return next()
})

希望对你有帮助!

关于vue.js - vuejs beforeRouteEnter。如果用户已登录,则禁用转到 url,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52328416/

相关文章:

javascript - 如何在 vue.js 中按字母和数字对表格进行排序?

php - "The sender hasn' t 已使用 sendgrid 验证此消息”

javascript - 带后退按钮的 Vue.js 路由

javascript - 尝试重用 vue.js 中的组件

vue.js - 如何在Vue中将颜色作为 Prop 发送?

security - OAuth 和 SSO 功能

vue.js - 使用 vue-router 传递隐藏数据

javascript - 如何让 iframe 在后台保持活跃?

vue.js - Vuejs 不同种类的入口点令人困惑

java - Spring Security 登录页面