vue3使用多语言

安装

npm install vue-i18n@9 -S || yarnadd vue-i18n@9

src目录下新建lang文件夹

在lang文件夹下新建index.js、zh.js、en.js

zh.js
module.exports = {
    name:'中文简体',
}
en.js
module.exports = {
    name:'English',
}
index.js
import En from '../lang/en'  // 英语语言包
import Zh from '../lang/zh'  // 中文语言包
const messages = {
    'en-US': {...En },
    'zh-HK': {...Tc },
}
//键名为需要给后端传的参数名
// 使用
//  <div class=""> {{ $t('msg.test') }}</div>


//1.组件的模板中使用 $t()
//2.组件的js使用 i18n.t
//3.非组件中使用i18n.global.t
//4.切换组件还是要
import { createI18n } from 'vue-i18n'
const i18n = createI18n({
    // 使用 Composition API 模式,则需要将其设置为false
    legacy: false,
    // 全局注入 $t 函数
    globalInjection: true,
    locale:sessionStorage.getItem('lange') || 'zh-HK',
    messages,
    // 防止使用v-html=“$t(“”)”的xss警告
    warnHtmlMessage: false
})
export default i18n
main.js
import { createApp } from 'vue'
import App from './App.vue'
import i18n from './utils/i18n.js'


createApp(App)
    .use(i18n)
    .mount('#app')
使用
<template>
    <button type="button" @click="changeLang('zh')">点击切换中文</button>
    <button type="button" @click="changeLang('en')">点击切换英文</button>
    <h2>{{ $t("title") }}</h2>
    <h2>{{ title }}</h2>
</template>

<script setup>
  import { ref, computed , getCurrentInstance} from "vue";
  import { useI18n } from "vue-i18n";
  const { locale} = useI18n(); //当前语言
  const { $t } = getCurrentInstance().proxy;
  const changeLang = (value: string) => {
    locale.value = value;
  };
  
  // 使用计算属性实现响应式
  const title = computed(() => $t("title"));
  
  const changeLang = (value: string) => {
    locale.value = value;
  };
</script>
  
<style scoped>
</style>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值