vue项目里多语言工具一直用的vue-i18n。
以前用的 vue2,也没啥大问题,就是配置好之后用t(“你的属性名”)就行,现在用vue3其实本来也没太大变化。
但是配置完之后,在html中用$t()没有问题,显示文案什么的一切正常。而在ts中使用$t()方法报错,后来才发现是我没有设置全局的$t()方法。

vue3中使用vue-i18n(ts中使用$t, vue3不用this)
记录一下在vue3中使用vue-i18n的方法:

  1. 安装vue-18n
  2. 配置
  3. 应用
  4. 挂载全局方法$t以方便在ts中使用(本次记录的重点)

由于1.2.3.好多人写过了,我就简单的写一下,本次记录的重点是4,因为我发现网上好多博客都只写了$t在html中的使用,但是大都没提到在ts中也可能用到。

  1. 安装
npm install vue-i18n@next 或 yarn add vue-i18n@next
  1. 在 src 目录下新建 lang 并新建 index.ts 文件
import App from '@/App.vue'
import { createApp } from 'vue'
import { createI18n } from 'vue-i18n'
import enLocale from './en/index';
import zhLocale from './zh/index';
const messages = {
    zh: zhLocale,
    cn: zhLocale,
    en: enLocale,
    us: enLocale,
}
const localLang = navigator.language.split('-')[0];
const storageLang = window.localStorage.getItem('locale')?.split('"')[1].split('"')[0].toLocaleLowerCase() || 'en';
const c = (storageLang.toLocaleLowerCase() !== 'zh' && storageLang.toLocaleLowerCase() !== 'en') ? 'en' : storageLang;
const i18n = createI18n({
    globalInjection: true, //全局生效$t
    locale: c || localLang || 'en',
    messages,
    legacy: false,
})
const app = createApp(App)
app.use(i18n)

vue3中使用vue-i18n(ts中使用$t, vue3不用this)

上图中两个语言包的index.ts中的内容自己根据语言需要写:

export default {
    nNation: 'Country/Region',
    pleaseInput: 'Account',
}
  1. 在ts中使用全局方法$t
import { getCurrentInstance } from "vue";
const { appContext : { config: { globalProperties } } } = getCurrentInstance();  // 这里可以根据需要写个hook
console.log(globalProperties.$t('pleaseSelectNation'))

在html中的使用就比较正常了:

<span>{{ $t("nation") }}</span>

其实本文算是新手记录一下对于globalProperties的使用,希望对您有所帮助。

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。