Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to export Router instance in Vue.js 2

I'm creating a Router instance in order to implement a routing system in my app. So, I'm doing it in such a way:

import Vue from 'vue'
import Router from 'vue-router'

Vue.use(Router)

export default new Router({
  routes: [
    {
      path: '/',
      name: 'Home',
      component: Home
    },
  ]
})

But I also need to implement a .beforeEach() hook on my Router instance. What's the workaround?

I find the way like:

router.beforeEach((to, from, next) => {
    // ...
});

But I guess in my case it won't be correct? What's the proper way of doing it?

like image 765
Камилов Тимур Avatar asked Feb 13 '18 05:02

Камилов Тимур


1 Answers

Solved:

import Vue from 'vue'
import Router from 'vue-router'

Vue.use(Router)

const router = new Router({
  routes: [
    {
      path: '/',
      name: 'Home',
      component: Home
    },
  ]
})

Implementing .beforeEach() hook on router instance:

router.beforeEach((to, from, next) => {
  if(to.meta.requiresAuth) { 
    if(store.state.session.authenticated) { 
        next();
    }
    else {
        next('/admin/login');
    }
  }
  else {
    next();
  }
});

Exporting the instance:

export default router;
like image 182
Камилов Тимур Avatar answered Sep 19 '22 22:09

Камилов Тимур