Vue+TypeScript获取路由参数报错:Property 'params'不存在于Function类型
解决Vue中获取路由参数的TypeScript报错问题
错误原因
你混用了Composition API(setup)和Options API(data),导致TypeScript无法正确推断this.route的类型,误将其识别为Function类型,因此报错Property 'params' does not exist on type 'Function'。直接使用this.$route时出现相同错误,大概率是Vue Router的类型定义未被正确引入。
解决方案
方案1:统一使用Composition API(推荐)
直接在setup中获取路由参数,无需再用data:
<script lang="ts"> import { defineComponent } from 'vue'; import { useRoute } from 'vue-router'; export default defineComponent({ setup() { const route = useRoute(); // 若需要响应式,可使用ref包裹 // const errorCode = ref(route.params.errorCode); const errorCode = route.params.errorCode; return { errorCode, }; }, name: 'ErrorPage', }); </script>
方案2:统一使用Options API
确保Vue Router的类型被正确识别,有两种方式:
方式A:声明Vue扩展类型
<script lang="ts"> import { defineComponent } from 'vue'; import type { RouteLocationNormalized } from 'vue-router'; // 扩展Vue类型,让TypeScript识别$route declare module '@vue/runtime-core' { interface ComponentCustomProperties { $route: RouteLocationNormalized; } } export default defineComponent({ name: 'ErrorPage', data() { return { errorCode: this.$route.params.errorCode, }; }, }); </script>
方式B:临时类型断言(快速解决)
如果只是临时需要绕过类型检查,可以用类型断言:
<script lang="ts"> import { defineComponent } from 'vue'; import type { RouteLocationNormalized } from 'vue-router'; export default defineComponent({ name: 'ErrorPage', data() { return { errorCode: (this.$route as RouteLocationNormalized).params.errorCode, }; }, }); </script>
额外注意
确保已经安装了Vue Router的类型依赖:
npm install @types/vue-router --save-dev
同时检查tsconfig.json中是否包含types: ["vue-router"]配置,保证类型定义能被正确加载。
内容的提问来源于stack exchange,提问作者Pete
相关产品推荐
相关产品推荐

