javascript - Vue-router 与 Typescript 以及 beforeEnter 守卫,如何使用已验证的数据?
我正在使用 Vue 和 vue-router 以及 TypeScript,我有一个常见的情况,就是显示 Photo 组件的单个页面,我有一个带有 beforeEnter 守卫的路由,它会查询我的存储来查看请求的照片是否实际存在
{
name: 'photo',
path: '/photos/:id',
meta: {requiresAuth: true},
component: () => import('@/pages/Photo.vue'),
beforeEnter: (to, from, next) => {
const photos = usePhotos();
const requestedPhoto = photos.$state.photos.findIndex(p => p.uuid === to.params.id)
return requestedPhoto === -1 ? next({name: 'home'}) : next()
},
}
在我的示例中,我已经在 beforeEnter 中检查了请求的照片是否存在,现在如果一切顺利,用户就会进入组件内部。
在我的组件中,我又使用以下代码行从存储中获取照片
const photo = photoStore.photos.find(p => p.uuid === route.params.id)
现在 TS 会告诉我这张照片可能未定义,因为查找操作可能不会返回结果,然而我们已经从保护步骤中知道这张照片确实会被找到。
const photo = photoStore.photos.find(p => p.uuid === route.params.id)
const uuid = photo!.uuid
我可以使用 TypeScript 的非空断言,但 ESLint 不喜欢,它提醒我:ESLint: 禁止使用非空断言。(@typescript-eslint/no-non-null-assertion)
所以我在想,处理这种情况的最佳做法是什么?
答案#1
如果photo保证存在,那么这就是非空断言操作符的情况。ESLint 规则可以暂时禁用,因为它在这里没有什么实际作用。
如果 photo 不保证存在,那么使用非空断言操作符是不正确的,因为这可能导致运行时错误。这种情况适用于类型保护:
const photo = photoStore.photos.find(p => p.uuid === route.params.id)
if (photo) {
const uuid = photo.uuid // undefined excluded from photo type
...
} else {
....
}
