For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt, and this page is available as Markdown at /blog/vue/i18n.md.

Vue I18n 语言切换

需求场景

前期开发 Vue2 H5 项目时,需要对项目进行国际化处理,该项目是基于 Vue2+VantUI2.x 的移动端 H5 SPA 项目。网上查阅了相关资料,大多推荐使用 vue-i18n 国际化插件来实现不同语言的切换。经过测试,已基本实现 中文 和 英文 两种语言的切换。

现在主流的前端 UI 框架也支持语言国际化,若项目中使用 UI 框架比较多,建议参考 UI 官方文档来配置国际化。Vue I18n 通过简单的 API 来实现项目的国际化;该插件除了简单的翻译之外还支持 数字、日期时间 等本地化处理。

相关文档

I18n 官方文档

依赖安装


npm
yarn
pnpm
bun
deno
npm install vue-i18n

引入插件

引入插件
import Vue from "vue";

import VueI18n from "vue-i18n";

Vue.use(VueI18n);

基本设置

基本设置
const messages = {
    en: {
        message: {
            hello: "hello, world!",
        },
    },
    zh: {
        message: {
            hello: "你好,世界!",
        },
    },
};
代码示例
// 创建 VueI18n 实例
const i18n = new VueI18n({
    locale: "en", // 设置地区
    messages, // 设置地区信息
});

// 创建挂载 Vue 实例
new Vue({
    router,
    i18n,
    render: (h) => h(App),
}).$mount("#app");

// 更改为其它的 locale
i18n.locale = "zh";

页面使用

页面使用
<template>
    <div class="change_lang">
        <!-- 输入结果为:你好,世界! -->
        <h1>{{$t('message.hello')}}</h1>
    </div>
</template>

<script>
    export default {
        name: "ChangeLang",
        data() {
            return { langs: ["zh", "en"] };
        },
        methods: {
            handleLang() {
                this.$i18n.locale = "zh";
            },
        },
    };
</script>
注意事项

切换语言时,所有引用多语言的页面都会自动更新为对应的语言。初始化 Vue I18n 实例时要设置默认展示的语言。

总结

项目中使用多语言的情况还是比较常见的,该插件是 Vue 官方团队成员开发的多语言工具,具体配置可查阅官方文档,具体文档见上部 相关文档 模块。