如何在另一个文件中导入类属性-Vue / Typescript

时间:2019-05-09 10:33:17

标签: typescript vue.js

src / middlewares / auth.ts文件:

import { Vue } from 'vue-property-decorator'

export default class AuthGuard extends Vue {
  public guest(to: any, from: any, next: any): void {
    if (this.$store.state.authenticated) {
      next()
      console.log('authenticated')
    } else {
      next({
        path: '/dashboard'
      })
      console.log('not authenticated')
    }
  }
}

与auth.ts相同,但在JS版本中:

export default {
 guest(to, from, next) {
    if (this.$store.state.authenticated) {
      next()
      console.log('authenticated')
    } else {
      next({
        path: '/dashboard'
      })
      console.log('not authenticated')
    }
  }
}

在JS中,它可以按预期运行,但不适用于Typescript。

我想在AuthRoutes.ts中导入此类:

import Guard from '@/middlewares/auth'

export default [
  {
    path: '/',
    name: 'login',
    component: () => import('@/views/Login.vue'),
    beforeEnter: Guard.guest
  }
]

但是我收到一个错误:“类型'Authof'上不存在属性'来宾'。”仍然无法绕过这些TS类型。我想念什么?

1 个答案:

答案 0 :(得分:0)

如果您需要访问实例,请不要使用beforeEnter

property存在于component instance上,而不存在于class definition上。

beforeEnter无权访问该实例。

将逻辑放入组件的created()mounted()方法中,并在其前面加上this.

使用beforeRouteEnterbeforeRouteUpdate访问组件的this

beforeRouteEnter防护措施对此无权访问,因为在确认导航之前调用了该防护措施,因此甚至还没有创建新的输入组件。

但是,您可以通过将回调传递给next来访问实例。确认导航后,将调用该回调,并将组件实例作为参数传递给回调:

beforeRouteEnter (to, from, next) {
  next(vm => {
    // access to component instance via `vm`
  })
}

因此,您的示例

beforeRouteEnter (to, from, next) {
  next(vm => {
    vm.guest
  })
}

对于保留该组件的路线更改:

beforeRouteUpdate (to, from, next) {
  this.guest
}

官方文档

beforeRouteEnter (to, from, next) {
    // called before the route that renders this component is confirmed.
    // does NOT have access to `this` component instance,
    // because it has not been created yet when this guard is called!
  },
beforeRouteUpdate (to, from, next) {
    // called when the route that renders this component has changed,
    // but this component is reused in the new route.
    // For example, for a route with dynamic params `/foo/:id`, when we
    // navigate between `/foo/1` and `/foo/2`, the same `Foo` component instance
    // will be reused, and this hook will be called when that happens.
    // has access to `this` component instance.
  },