【发布时间】:2022-01-01 08:11:17
【问题描述】:
我正在使用带有 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)
所以我想知道,处理这种情况的最佳做法是什么?
【问题讨论】:
标签: javascript typescript vue.js vue-router