Nuxt集成TypeScript提示$router不存在,如何省略组件的Vue.extend声明
解决方案
你可以通过以下配置实现无Vue.extend包裹的普通组件导出写法的类型支持:
- 调整
tsconfig.json配置
首先确保基础编译配置和类型引入正确,新增Volar实验性隐式包裹配置:
{ "compilerOptions": { "strict": true, "esModuleInterop": true, "allowSyntheticDefaultImports": true, "moduleResolution": "Node", "types": [ "@nuxt/types", "@types/node", "vue-router" ] }, "include": [ "types/**/*.d.ts", "**/*.ts", "**/*.vue" ], "vueCompilerOptions": { "experimentalImplicitDefineComponent": true } }
开启experimentalImplicitDefineComponent后,Volar会自动将.vue文件中普通导出的对象视为被defineComponent包裹,自动推导组件的data、props、上下文属性(含你扩展的$router、$route)的类型。
- 可选稳定替代方案
如果不想使用实验性特性,可以通过unplugin-auto-import实现defineComponent全局自动导入,不需要手动写引入语句和Vue.extend,写法仅多一层defineComponent包裹,类型推导更稳定:
<script lang="ts"> // 无需手动导入defineComponent export default defineComponent({ data() { return { property1: '' } } }) </script>
你已经编写的vue-shim.d.ts配置无需修改,只要确保types目录被tsconfig.json的include规则覆盖即可正常生效。
内容的提问来源于stack exchange,提问作者JG_GJ
相关产品推荐
相关产品推荐

