`this` 在 vue-router beforeEach 中未定义 [英] `this` undefined in vue-router beforeEach

查看:78
本文介绍了`this` 在 vue-router beforeEach 中未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过this.a.app 访问 vue-router 中的会话,但它弹出 1 个错误.在我调试之后,我发现 this 是未定义的.这是我用来显示this的代码.

I'm trying to access the session in vue-router viathis.a.app, but it pops out 1 error. After i debug, i found out that this is undefined. this is the code im using to show this.

我曾尝试使用 function(to, from, next) {...} 而不是 es6 语法,但 this 仍未定义.

I had tried to use function(to, from, next) {...} instead of es6 syntax, but this is still undefined.

router.beforeEach((to, from, next) => {
  if (!to.meta.isPublic){
    // eslint-disable-next-line
    console.log(this)
  }
  next()
})

是否需要进行任何配置以便我可以在 vue-router 中访问 this?

Is there any configuration i need to make so that i can access this in vue-router?

推荐答案

是的,您可以在路由器内使用this"访问 beforeEach 钩子,但方式不同.路由器具有插入它的根实例

Yes, you can use access "this" inside router beforeEach hook, but in a different way. The router has the root instance from where it is inserted

用户 router.app 它指向this"(根 Vue 实例)

User router.app it is pointing to "this" (the root Vue instance)

 router.beforeEach((to, from, next) => {
  if (!to.meta.isPublic){
    // eslint-disable-next-line
    console.log(router.app)
  }
  next()
})

这篇关于`this` 在 vue-router beforeEach 中未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆