![](/img/trans.png)
[英]How to access async store data in vue-router for usage in beforeEnter hook?
[英]Vue-router with Typescript and beforeEnter guard, how to use validated data?
我正在使用带有 typescript 的 Vue 和 vue-router,我有一个常见的情况,即要显示照片组件的单个页面,我有一个带有 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: Forbidden non-null assertion.(@typescript-eslint/no-non-null-assertion)
所以我想知道,处理这种情况的最佳做法是什么?
如果photo
保证存在,则非空断言运算符就是这种情况。 ESLint 规则可以暂时禁用,因为它在这里没有很好的用途。
如果不保证photo
存在,则使用非空断言运算符是不正确的,因为这会导致运行时错误。 这是类型保护的情况:
常量照片 = photoStore.photos.find(p => p.uuid === route.params.id)
if (photo) {
const uuid = photo.uuid
...
} else {
....
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.