Is there a way to accees vue js VueSession in main.js

Viewed 298

I have the folllowing setup in main.js:

import Vue from 'vue'
import App from './App.vue'
import VueRouter from 'vue-router'
import Home from './views/Home.vue'
import Login from './views/Login.vue'
import Profile from './views/Profile.vue'
import Simulations from './views/Simulations.vue'
import VueSimpleAlert from "vue-simple-alert"
import StatisticPage from './views/StatisticPage.vue'
import VueSession from 'vue-session'
import Users from './views/Users.vue'

Vue.use(VueSimpleAlert)
Vue.use(VueRouter)
Vue.use(VueSession)

Vue.config.productionTip = false

const routes = [
  {path: '/', name:'Login', component: Login },
  {path: '/users', name:'Users', component: Users},
  {path :'/home', name:'Home', component: Home},
  {path: '/subject/:Pid', name: 'Profile', component: Profile},
  {path: '/subject/:Pid/simulations', name:'Simulations', component: Simulations},
  {path: '/subject/:Pid/simulations/:Sid/statistics', name:'Statistics', component: StatisticPage}
]

const router = new VueRouter({
  routes,
  mode: 'history'
})

router.beforeEach((to, from, next) => {
  if(to.name !== 'Login'){
    if(this.$session.get('token')){
      next()
    }else{
      next({ name: 'Login'})
      next()
    }
  }else{
    next()
  }
})

new Vue({
  router,
  render: h => h(App),
}).$mount('#app')

export default router

As you can see I am trying to access the session information but I keep getting the error that $session is undefined. How can I access the session information in the router here?

1 Answers

if you wanna access Vue instance inside your router use router.app instead of this

change this line :

this.$session.get('token')

to this:

router.app.$session.get('token')

you can read more about Router Instance Properties in : https://router.vuejs.org/api/#router-instance-properties

Related