Sanya
Sanya

Reputation: 95

vuejs beforeRouteEnter. Disable go to url if user is logged in

I want disable go to url "login" if user is logged in. I no use vuex. And I send ajax from method "beforeRouteEnter"(check login and maiby get data on page), but before, I go to route(I can see html component login page and url "/login") and after redirect from this page.

How to do what I did not go to the specified URL at all?

    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("/");
                    }
                });
        });
    }

Upvotes: 2

Views: 2897

Answers (1)

Thomas Lombart
Thomas Lombart

Reputation: 433

You may want to take a look at router.beforeEach instead of beforeRouteEnter. In fact, as the docs specify it : beforeRouteEnter is called before the route that renders this component is confirmed.

Here is how you would do it with 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()
})

Hope it helps!

Upvotes: 3

Related Questions