Skip to content

Instantly share code, notes, and snippets.

@techlab23
Last active February 28, 2018 05:44
Show Gist options
  • Save techlab23/e844cfb9e23d132d0546780e28a04ef2 to your computer and use it in GitHub Desktop.
Save techlab23/e844cfb9e23d132d0546780e28a04ef2 to your computer and use it in GitHub Desktop.
Vue Router with home component
import Vue from 'vue'
import Router from 'vue-router'
// Importing Home component
import Home from '@/components/Home'
// Importing login component
import Login from '@/components/shared/Login'
// Importing our store to get access to getters
import store from '../store'
Vue.use(Router)
let router = new Router({
// Enabling history mode and clean urls without #! (hash bang)
mode: 'history',
// Defining our application routes
routes: [
// Catch all route to redirect user to login page
{
path: '*',
redirect: '/login'
},
// Securing all application routes even the / route, redirect to login page
{
path: '/',
redirect: 'login'
},
// Login route. This route does not require authentication
{
path: '/login',
name: 'Login',
component: Login
},
// Home route. This is a protected route. Only authenticated user can access it.
// using meta.requiresAuth = true to denote authentication requirements
{
path: '/home',
name: 'Home',
component: Home,
meta: {
requiresAuth: true
}
}
]
})
// Navigation guard (beforeEach) will execute before each navigation.
// If the route requires Authentication and user is not logged in, then send the user to login route.
// If the route does not require and user is logged in, then send the user to home route.
// Otherwise let user to navigate the app.
router.beforeEach((to, from, next) => {
// Check if the user information is available
let hasCurrentUser = store.getters.hasCurrentUser
// Check if target route require authentication
let requiresAuth = to.matched.some(record => record.meta.requiresAuth)
// if route requires authentication and user is not logged in then redirect to login route
if (requiresAuth && !hasCurrentUser) next('login')
// This will catch 404 not found routes as well
else if (!requiresAuth && hasCurrentUser) next('home')
// otherwise let the user access the route
else next()
})
// Exporting the router instance
export default router
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment