Reputation: 79
Say I just started a vue-nodejs-webpack simple project with vue cli:
vue create xxx
How should I plug its default client-side routing to allow certain routes based on authentication? in the most idomatic way?
My App.vue will look something like this:
<template>
<v-app class="grey lighten-4">
<Navbar />
<v-content class="mx-4 mb-4">
<router-view></router-view>
</v-content>
</v-app>
</template>
Whereas "Navbar" is a simple top navigation menu, and router-view simply shows content based on current route.
Route.js will look like this:
import Vue from 'vue'
import Router from 'vue-router'
import Dashboard from './views/Dashboard.vue'
import Projects from './views/Projects.vue'
import Team from './views/Team.vue'
Vue.use(Router)
export default new Router({
mode: 'history',
base: process.env.BASE_URL,
routes: [
{
path: '/',
name: 'dashboard',
component: Dashboard
},
{
path: '/projects',
name: 'projects',
component: Projects
},
{
path: '/team',
name: 'team',
component: Team
}
]
})
Upvotes: 1
Views: 157
Reputation: 5260
In roter.js, you can use vue-router hooks to have precise control on route whether to render components or not
Here in the below example isAunthenticated
is a separate javascript function which returns boolean, by checking in the backend whether the user is authenticated or nor
router.beforeEach((to, from, next) => {
if (!isAuthenticated) next('/login')
else next()
})
At the same time you can also use pre router hooks to prevent the user to enter specific route
const router = new VueRouter({
routes: [
{
path: '/foo',
component: Foo,
beforeEnter: (to, from, next) => {
// ...
}
}
]
})
Also you can use In-Component Guards at specific components to verify whether the user has specific access to this component or not
Upvotes: 1