vue3的多语言脚本(vue-i18n)的各种场景

引入vue-i18n依赖文件

cnpm install vue-i18n@next

多语言的使用文件夹结构和核心文件处理

目录结构

en.ts文件

export default {
  common: {
    submitBtn: 'Submit'
  }
 }

zh.ts文件

export default {
  common: {
    submitBtn: '确定'
  }
 }

index.ts文件

import { createI18n } from "vue-i18n"
import zh from "./lang/zh"
import en from "./lang/en"

const i18n = createI18n({
	locale: localStorage.getItem("locale") || navigator.language.slice(0, 2),
	legacy: false,
	globalInjection: true, //全局生效$t
	messages: {
		zh,
		en
	}
})
export default i18n

引入场景

非库文件main.ts

import { createApp } from 'vue'
import App from './App.vue'
import locale from "./locale"
const app = createApp(App)
app.provide("$tt", locale.global.t)
app.use(locale)
app.mount('#app')

库文件index.ts

import { getCurrentInstance } from "vue"
import locale from "./locale"
export default {
	install(app: App, opts: any = {}): void {
		app.provide("$tt", locale.global.t) //多语言到ts中使用,模板中直接通过$t("")进行使用,或t("")
		app.use(locale) //多语言的挂载
	}
}

使用

在vue的template中使用

方案一
<div>{{$t("common.submitBtn")}}</div>
方案二
<template><div>{{ttttt("common.submitBtn")}}</div></template>
<script setup lang="ts">
import {  inject } from "vue";
const ttttt: any = inject("$tt");
</script >

在vue的script部分使用

<script setup lang="ts">
import {  inject } from "vue";
const ttttt: any = inject("$tt");
const onXXXXX = () => {
    console.log("测试:", ttttt("common.submitBtn"));
};
</script >

在外部ts使用

import locale from "../locale"
const tt = locale.global.t
export function xxx() {
    console.log("xxxxx", tt("common.submitBtn"))
    return "222"
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

yll1024335892

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值