在带有 TypeScript 的 Nuxt/Vue 模板中使用路由查询参数时出错

问题描述 投票:0回答:1

我正在使用 TypeScript 开发 Nuxt.js 项目,并遇到路由查询参数的问题。具体来说,TypeScript 给我一个与名为 userType 的路由查询参数相关的类型错误。

当我尝试在 NuxtLink 组件中将 userType 作为查询参数传递时,就会出现问题:

<NuxtLink
    :to="localePath({ name: 'account-upload-images', query: { userType: retrievedUserType } })"
    class="skip-for-now"
>
    {{ $t('sign_up.cta.skip_for_now.label') }}
</NuxtLink>

这里,retrievedUserType 是一个计算属性,我希望它是一个字符串。错误发生在这一行,指出:“类型‘unknown’不能分配给类型‘string | (string | null)[] | null | undefined’。”

我有一个函数 getSignedUpAs ,它可靠地返回一个字符串,用于设置 userType 路由查询参数:

const getSignedUpAs = (): string => {
    return formData.signed_up_as.split('--')[0];
};

const userType = getSignedUpAs();

router.push({
    name: 'account-instagram-approval',
    query: { userType: userType },
});

在 account-instagram-approval 组件中,我尝试从路由查询中检索 userType:

<script lang="ts">
import { computed, defineComponent, ref, useRoute } from 
'@nuxtjs/composition-api';

    export default defineComponent({
        name: 'account-instagram-approval',
        setup() {
            const route = useRoute();
       const retrievedUserType = computed(() => {
            return route.value.query.userType as string;
        });
    
            return { retrievedUserType };
        },
    });
    </script>

尽管进行了这些尝试,我仍然面临相同的 TypeScript 错误。我尝试了多种解决方案,包括:

  1. 使用字符串进行显式类型转换。
  2. 用空字符串初始化retrievedUserType,然后 根据路线查询有条件地分配它。
  3. 使用计算属性将路由查询参数返回为 一根绳子。

我需要确保retrievedUserType被视为组件内的字符串。有人可以帮助我理解为什么我会收到此 TypeScript 错误以及如何解决它吗?任何在 Nuxt/Vue 中使用 TypeScript 处理路由查询参数的见解或替代方法将不胜感激。

我注意到,如果我在模板中添加类型:

<NuxtLink
    :to="localePath({ name: 'account-upload-images', query: { userType: retrievedUserType as string } })"
    class="skip-for-now"
>
    {{ $t('sign_up.cta.skip_for_now.label') }}
</NuxtLink>

Visual Studio Code 不会对我大喊大叫,但当我运行该应用程序时,我会收到此错误:

编译模板时出错:

无效表达式:

中出现意外标识符
localePath({ name: 'account-upload-images', query: { userType: retrievedUserType as string } })

我可以理解为什么会发生这种情况,但是如果我在任何地方都将查询参数转换为字符串,为什么 TS 仍然将查询参数转换为“未知”。

javascript typescript vue.js nuxt.js vue-router
1个回答
0
投票

我解决这个问题的方法是,我没有直接在模板上使用路由查询,而是在 NuxtLink 上创建了一个事件,并构建了重定向到那里的路由:

    <NuxtLink :to="uploadImagesLink" class="skip-for-now">
        {{ $t('sign_up.cta.skip_for_now.label') }}
    </NuxtLink>

方法:

    const uploadImagesLink = computed(() => {
        return context.root.localePath({
            name: 'account-upload-images',
            query: { userType: userType.value },
        });
    });

仍在尝试找出为什么 TS 在使用模板上的查询参数时,这种实现会出现这么多问题。

© www.soinside.com 2019 - 2024. All rights reserved.