typescript - 如何在另一个文件中导入类属性 - 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 类型。我想念什么?
解决方案
beforeEnter
如果您需要访问实例,请勿使用。
property
存在于 上,component instance
而不存在于 上class definition
。
beforeEnter
无权访问该实例。
将您的逻辑放在组件的created()
ormounted()
方法中,并在其前面加上this.
.
使用beforeRouteEnter
andbeforeRouteUpdate
访问组件的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.
},
推荐阅读
- r - R闪亮:由于超时限制,屏幕变灰
- mongodb - findOneAndUpdate - 在同一查询中查找视图并更新集合?
- php - Guzzle 发出 GET 请求而不是 POST
- c++ - 安装 OpenCV-4.3 windows 时 Mingw32-make 安装错误
- javascript - 是否可以在快速路由器中使用应用程序级中间件?
- java - 如何使用简单的 json 读取 Java 中的 JSON 文件?
- react-native - Expo React Native - 如何使用 ErrorRecovery?
- postgresql - 并发创建唯一索引时的 Postgres lock_timeout
- javascript - 带有 d3.js(v5)色标的谷歌地图不起作用
- python - 如何在 Django 中减去两个日期?