posts - 608,  comments - 13,  views - 63万
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
来源:https://blog.csdn.net/m0_66532594/article/details/128376057
https://blog.csdn.net/weixin_51220466/article/details/123889240

1.npm i vue-i18n 或 cnpm i vue-i18n
2.创建 il18n
在src目录下创建 i18n 文件夹,并在下面分别创建三个语言文件 :
index.js => 主文件用于导入 i18n 和相关配置
zh.js => 存放中文内容
en.js => 存放英文内容

index.js 示例:
import { createI18n } from 'vue-i18n';
import ZH from './zh.js';
import EN from './en.js';
const messages = {
zh: { ...ZH },
en: { ...EN },
};

const i18n = createI18n({
legacy: false,
globalInjection: true,
locale: 'zh',
messages
});
export default i18n;

locale属性用于设置初始语言,值要和 messages 中的属性 key ,相互对应。

zh.js 示例
export default {
person: {
name:'张三',
hobby:'唱跳,rap,篮球'
},
};

en.js 示例
export default {
person: {
name:'zhangsan',
hobby:'Singing and dancing, rap, basketball'
},
};

3.在main.js 中配置 i18n
import { createApp } from "vue";
import App from "./App.vue";
import i18n from './i18n/index';
const app = createApp(App);
app.use(i18n).mount("#app");

4.使用
4.1如果只是在 html 中使用,不用在导入任何东西
<template>
<div>
<span> {{ $t("person.name") }} </span>
<span> {{ $t("person.hobby") }} </span>
</div>
</template>
4.2在js 中使用,需要通过导入 getCurrentInstance 进行获取
<script setup>
import { getCurrentInstance } from "vue";
const { $t } = getCurrentInstance().proxy;
console.log( $t("person.name") ); //获取值
</script>

5.修改语言和获取当前语言
切换语言要导入vue-i18n 的 locale 属性,locale 是ref 对象,要修改value
不要修改 i18n/index.js文件, 导出的对象属性
<script setup>
import { useI18n } from 'vue-i18n'
const { locale } = useI18n()
// 切换中文
function changeZh(){ locale.value = 'zh'; };
// 切换英文
function changeEn(){ locale.value = 'en'; };
</script>

posted on   邢帅杰  阅读(1969)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
历史上的今天:
2018-05-11 bootstrap日历控件
点击右上角即可分享
微信分享提示