如何在Nuxt的Vuex Store中注入插件功能且不出现TypeScript错误
问题原因
这个报错属于TypeScript类型定义缺失问题,运行时功能正常是因为Nuxt的inject方法确实已经将$customAxios挂载到了Vuex的Store实例上,只是TypeScript默认的Store类型定义中没有包含你自定义注入的属性,所以需要手动扩展类型声明。
解决步骤
1. 新增自定义类型声明
在项目根目录新建types文件夹,在文件夹内创建index.d.ts类型声明文件,写入以下内容:
import type { AxiosPromise } from 'axios' // 扩展Vuex Store的类型,解决action中this.$customAxios的类型报错 declare module 'vuex/types/index' { interface Store<S> { $customAxios: { get: <T = any>(path: string, params?: Record<string, any>) => AxiosPromise<T> post: <T = any>(path: string, data?: Record<string, any>) => AxiosPromise<T> } } } // 可选:扩展Nuxt上下文和Vue实例类型,方便其他场景调用$customAxios declare module '@nuxt/types' { interface NuxtAppOptions { $customAxios: { get: <T = any>(path: string, params?: Record<string, any>) => AxiosPromise<T> post: <T = any>(path: string, data?: Record<string, any>) => AxiosPromise<T> } } interface Context { $customAxios: { get: <T = any>(path: string, params?: Record<string, any>) => AxiosPromise<T> post: <T = any>(path: string, data?: Record<string, any>) => AxiosPromise<T> } } } declare module 'vue/types/vue' { interface Vue { $customAxios: { get: <T = any>(path: string, params?: Record<string, any>) => AxiosPromise<T> post: <T = any>(path: string, data?: Record<string, any>) => AxiosPromise<T> } } }
提示:如果项目中还没有安装Nuxt相关的类型依赖,先运行
npm i -D @nuxt/types @types/axios安装即可。
2. 修改tsconfig.json配置
在项目根目录的tsconfig.json中添加自定义类型的扫描路径,确保TypeScript能读取到你新增的声明文件:
{ "compilerOptions": { // 其余原有配置保持不变 "typeRoots": [ "node_modules/@types", "./types" ] }, "include": [ // 其余原有include项保持不变 "types/**/*.d.ts" ] }
3. 可选:优化插件类型
将原有的plugins/axios.js重命名为plugins/axios.ts,给参数添加类型注解避免插件内部的类型报错:
import type { Context } from '@nuxt/types' export default function ({ $axios, redirect }: Context, inject: (key: string, value: any) => void) { // 原有插件逻辑保持不变 }
4. 生效配置
如果使用VSCode,按下Ctrl+Shift+P选择TypeScript: Restart TS Server重启TypeScript服务,或者直接重启编辑器,报错就会消失。
内容的提问来源于stack exchange,提问作者Cio Casado
相关产品推荐
相关产品推荐

