本文介绍了有没有办法在 main.js 中访问 vue js VueSession的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在 main.js 中有以下设置:
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
如您所见,我正在尝试访问会话信息,但一直收到 $session 未定义的错误消息.这里如何访问路由器中的会话信息?
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?
推荐答案
如果你想访问路由器内部的 Vue 实例,请使用 router.app
而不是 this
if you wanna access Vue instance inside your router use router.app
instead of this
改变这一行:
this.$session.get('token')
为此:
router.app.$session.get('token')
您可以在以下位置阅读有关路由器实例属性的更多信息:https://router.vuejs.org/api/#router-instance-properties
这篇关于有没有办法在 main.js 中访问 vue js VueSession的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!