uni-app 国际化i18n在typeScript编译报错

uni-app 国际化i18n在typeScript编译报错

示例代码:

<script lang="ts" setup>
import { ref, computed, getCurrentInstance } from 'vue'
import { onLoad } from '@dcloudio/uni-app'  

// 获取当前实例  
const { proxy } = getCurrentInstance()  

const text = proxy.$t('index.demo')  
console.log(text)  
</script>

操作步骤:

  • 项目编译报错

预期结果:

  • 希望正常

实际结果:

  • TypeError: proxy.$t is not a function

bug描述:

国际化(i18n)在typeScript编译报错 main.js:34 TypeError: proxy.$t is not a function


| 项目属性           | 值          |
|-------------------|-------------|
| 产品分类           | uniapp/App  |
| PC开发环境操作系统 | Windows     |
| PC开发环境版本号   | 10          |
| HBuilderX类型      | 正式        |
| HBuilderX版本号    | 4.76        |
| 手机系统           | 全部        |
| 手机厂商           | 华为        |
| 页面类型           | vue         |
| vue版本            | vue2        |
| 打包方式           | 云端        |
| 项目创建方式       | HBuilderX   |

更多关于uni-app 国际化i18n在typeScript编译报错的实战教程也可以访问 https://www.itying.com/category-93-b0.html

1 回复

更多关于uni-app 国际化i18n在typeScript编译报错的实战教程也可以访问 https://www.itying.com/category-93-b0.html


在 uni-app 中使用 TypeScript 时,getCurrentInstance() 返回的 proxy 类型可能不包含 $t 方法,导致编译报错。这是因为 TypeScript 无法自动推断出 Vue 实例上的自定义属性。

解决方案:

  1. 类型声明扩展
    在项目中创建 shims-vue.d.ts 文件(如未存在),添加以下内容以扩展 Vue 实例类型:

    declare module '[@vue](/user/vue)/runtime-core' {
      interface ComponentCustomProperties {
        $t: (key: string) => string
      }
    }
    
  2. 使用替代方法获取实例
    避免直接使用 proxy,改用 vue-i18nuseI18n 组合式函数(需确保已正确安装配置):

    <script lang="ts" setup>
    import { useI18n } from 'vue-i18n'
    
    const { t } = useI18n()
    const text = t('index.demo')
    console.log(text)
    </script>
    
  3. 检查 i18n 安装配置
    确认已在 main.ts 中正确挂载 i18n 实例:

    import { createApp } from 'vue'
    import App from './App.vue'
    import i18n from './locale'
    
    const app = createApp(App)
    app.use(i18n)
    app.mount('#app')
回到顶部