How to give access to page in Vue.js only if a user is logged in / localStorage exists?

Viewed 5621

I currently have a simple Vue.js application, I am using vue-router like this. index.html

<p>
  <router-link to="/" exact> Home </router-link>
  <router-link to="/about"> About </router-link>
  <router-link to="/contact"> Contact </router-link>
  <router-link to="/login"> Login </router-link>
  <router-link to="/register"> Register </router-link>
</p>
<router-view></router-view>

And I have this in my /routes.js

import VueRouter from 'vue-router';

let routes = [
  {
    path: '/',
    component: require('./components/Home.vue')
  },
  {
    path: '/about',
    component: require('./components/About.vue')
  },
  {
    path: '/login',
    component: require('./components/Login.vue')
  },
  {
    path: '/register',
    component: require('./components/Register.vue')
  }
];

export default new VueRouter({
  mode: 'history',
  routes
});

I have index.js file which initialized the app, I think I should do something within my created(){} module but I am not sure how it is done.

I can set/unset sessions, all I need to know is how to give access to a page only if this session exists.

1 Answers
Related