【问题标题】:Vue-router with Typescript and beforeEnter guard, how to use validated data?带有Typescript和beforeEnter保护的Vue-router,如何使用经过验证的数据?
【发布时间】: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


    【解决方案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 {
      ....
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-15
      • 2017-07-23
      • 2014-11-07
      • 2019-09-29
      • 1970-01-01
      • 2018-07-12
      • 2020-05-07
      • 1970-01-01
      相关资源
      最近更新 更多