![](/img/trans.png)
[英]How to use plugins like vue-resource when using Vue.js with Typescript?
[英]How to use vue-resource in navigation guard
我正在尝试使用路由器内部的vue-resource
通过令牌获取有关用户的信息,以保护某些路由:
router/index.js
:
const router = new Router({
mode: 'history',
linkExactActiveClass: 'is-active',
routes: [
{
path: '/login',
name: 'Login',
component: Login
},
{
path: '/board',
name: 'Board',
component: Board,
meta: {
requiresAuth: true
}
}
]
})
router.beforeEach((to, from, next) => {
// check if rout requires auth
if (to.matched.some(rec => rec.meta.requiresAuth)) {
const token = localStorage.getItem('user-token')
if (token == null) {
next({ name: 'Login' })
}
else {
this.$http.get('/rest-auth/user/', {headers: {"Authorization": "Token " + token}})
.then(response => { next() }, response => { next({ name: 'Login' }) });
}
}
else {
next()
}
})
但是,当我尝试登录时遇到错误: TypeError: Cannot read property 'get' of undefined
,因此我试图像这样解决它来访问vm实例:
router.beforeEach((to, from, next) => {
// check if rout requires auth
if (to.matched.some(rec => rec.meta.requiresAuth)) {
const token = localStorage.getItem('user-token')
if (token == null) {
next({ name: 'Login' })
}
else {
next(vm => {
vm.$http.get('/rest-auth/user/', {headers: {"Authorization": "Token " + token}})
.then(response => { next() }, response => { next({ name: 'Login' }) });
})
}
}
else {
next()
}
})
但是它也不起作用,所以也许我需要切换到axios
来做到这一点?
我很确定您需要import vue-resource from 'vue-resource'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.