Vue-router: beforeEnter fire twice on root path ('/') after async `next` call

Created on 5 Oct 2016  ·  5Comments  ·  Source: vuejs/vue-router

Hi, when my app start, beforeEnter is fired twice, dunno why. And since i'm using socket, after this all my sockets emit twice. Am I missing something ?

I'm using vue 2.

UPDATE: this seems to occur because of asynchronous calls in my function.
See this fiddle: https://jsfiddle.net/1xb99hz6/

This is my code :

import Vue from 'vue'
import VueRouter from 'vue-router'
import VueResource from 'vue-resource'
import socket from './services/socket'
import {auth} from './services/auth'

// import vue componenets
import App from './routes/app.vue'
import Signin from './routes/signin.vue'
import Signup from './routes/signup.vue'

// init all the things
Vue.use(VueRouter);
Vue.use(VueResource);
Vue.use(socket.install);

// config routes
const router = new VueRouter({
   base: __dirname,
   linkActiveClass: 'active-link',
   routes: [
     { path: '/', beforeEnter: auth, component: App},
     { path: '/signin', component: Signin },
     { path: '/signup', component: Signup }
   ]
});

// mount a root Vue instance
new Vue({
   router,
}).$mount('#app');

And my auth function :

function auth(to, from, next) {

   console.log('in auth');

   // if no internet connection
   if (!navigator.onLine) {
      next('/nointernet');
   }

   const jwt = getToken();

   if (jwt) {

      // send the jwt
      socket.emit('authenticate', {token: jwt}) ;

      // if user is authenticated
      socket.once('authenticated', (token) => {
         next();
      });

      // if user is unauthorized
      socket.once('unauthorized', () => {
         removeToken(tokenKey);
         next('/signin');
      });

   } else {
      next('/signin');
   }

}

in console I get 'in auth' twice in a really short amount of time.

2.x bug

Most helpful comment

Still happens to me, vue 2.3.4, vue-router 2.6.0

All 5 comments

Hi, thanks for filling this issue. Please follow the Issue Reporting Guidelines and provide a live example on jsfiddle, codepen etc. Thanks!

The problem occur when I'm doing an asynchronous call in the beforeEnter function.
See this fiddle: https://jsfiddle.net/1xb99hz6/

Strangely, it happens only on the root path, and only after async next call.. https://jsfiddle.net/2qv45zcq/
Looks like a bug to me.

Closed via #735 - thanks for fixing your own issue! :D

Still happens to me, vue 2.3.4, vue-router 2.6.0

Was this page helpful?
0 / 5 - 0 ratings