简体   繁体   English

如何在Navigation Guard中使用Vue资源

[英]How to use vue-resource in navigation guard

I'm trying to use vue-resource inside my router to get info about the user by token to protect some routes: 我正在尝试使用路由器内部的vue-resource通过令牌获取有关用户的信息,以保护某些路由:

router/index.js : 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()
  }
})

But I'm getting error when I'm trying to log in: TypeError: Cannot read property 'get' of undefined , so I've tried to solve it like this to get access to vm instance: 但是,当我尝试登录时遇到错误: 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()
  }
})

But it's not working also, so maybe i need to switch to axios to do it? 但是它也不起作用,所以也许我需要切换到axios来做到这一点?

我很确定您需要import vue-resource from 'vue-resource'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM