首页 > 解决方案 > 如何在另一个文件中导入类属性 - Vue/Typescript

问题描述

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
  }
]

但是我收到一个错误:“类型'typeof AuthGuard'上不存在属性'guest'。” 仍然无法理解这些 TS 类型。我想念什么?

标签: typescriptvue.js

解决方案


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

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

beforeEnter无权访问该实例。

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

使用beforeRouteEnterandbeforeRouteUpdate访问组件的this.

beforeRouteEnter 守卫无权访问 this,因为在导航确认之前调用了守卫,因此新的进入组件甚至还没有创建。

但是,您可以通过将回调传递给 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.
  },

推荐阅读