You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue2迁移至Vue3后this.$系列API($t/$route等)报错求助

解决方案

1. 修正插件注册方式

Vue3 必须通过 app.use() 注册路由、i18n 等插件,而非直接传入 createApp 的选项对象。修改 main.ts:

import { createApp, h } from 'vue';
import App from './App.vue';
import router from './router';
import i18n from './i18n';

const app = createApp({
  render: () => h(App, { logo: '/img/sodra-logo.svg' }),
});

// 注册全局插件
app.use(router);
app.use(i18n);

app.mount('#app');

2. 调整 TypeScript 类型依赖

将 tsconfig.json 中 types 数组的 "vue" 替换为 "@vue/compat",确保 TypeScript 使用 Compat 模式的类型定义:

{
  "compilerOptions": {
    // ...其他配置
    "types": ["vite/client", "@vue/compat", "webpack-env", "jest"],
    // ...其他配置
  }
}

3. 声明全局属性类型

在 src 目录下创建 global.d.ts 文件,扩展 Vue 的类型接口,让 TypeScript 识别所有 $ 开头的全局属性:

import type { Router, RouteLocationNormalizedLoaded } from 'vue-router';
import type { I18n } from 'vue-i18n';
import moment from 'moment';

declare module '@vue/runtime-core' {
  interface ComponentCustomProperties {
    // 路由相关
    $router: Router;
    $route: RouteLocationNormalizedLoaded;
    // i18n 翻译方法
    $t: I18n['t'];
    $tc: I18n['tc'];
    // moment 全局方法
    $moment: typeof moment;
    // 其他自定义全局属性按需添加
  }
}

export {};

4. 确保版本一致性

检查 package.json 中 vue 和 @vue/compat 的版本完全一致(如均为 3.3.x),避免版本不兼容导致的类型错误:

{
  "dependencies": {
    "vue": "^3.3.4",
    "@vue/compat": "^3.3.4",
    "vue-router": "^4.2.5",
    "vue-i18n": "^9.2.2"
  }
}

5. 重启服务并清除缓存

修改配置后,重启 npm run serve,同时删除 node_modules/.cache 目录或清除 IDE 的 TypeScript 缓存,确保新配置生效。


问题根源

  • Vue3 插件必须通过 app.use() 注册才能全局注入 $router、$t 等属性,Vue2 直接传入选项的写法在 Vue3 中不会触发全局注入逻辑。
  • Compat 模式需要使用 @vue/compat 的类型定义,原生 Vue3 类型无法识别 Vue2 风格的全局 API。
  • 自定义全局属性(如 $moment)需要手动扩展类型接口,TypeScript 才会认可这些属性的存在。

内容的提问来源于stack exchange,提问作者novafluff

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 21:13:13