




















首先安装适合 Vue2 的 vue-i18n 版本(注意:Vue2 需使用 vue-i18n@8.x,Vue3 则用 vue-i18n@9+)
npm install vue-i18n@8 --save # 或 yarn add vue-i18n@8
在项目中创建语言包目录(例如 src/lang),并添加不同语言的配置文件:
export default { message: { hello: 'Hello', welcome: 'Welcome to {name}', // 支持变量 button: { submit: 'Submit', cancel: 'Cancel' } } }
export default { message: { hello: '你好', welcome: '欢迎来到 {name}', button: { submit: '提交', cancel: '取消' } } }
创建 src/lang/index.js 整合配置:
import Vue from 'vue' import VueI18n from 'vue-i18n' import en from './en' import zh from './zh' // 注册插件 Vue.use(VueI18n) // 实例化 const i18n = new VueI18n({ locale: 'zh', // 默认语言 fallbackLocale: 'en', // 语言切换失败时的备用语言 messages: { en, zh } }) export default i18n
在 main.js 中挂载 i18n 实例:
import Vue from 'vue' import App from './App.vue' import i18n from './lang' // 引入配置 new Vue({ el: '#app', i18n, // 挂载到实例 render: h => h(App) })
$t('键名')$t('键名', { 变量名: 值 })<template>
<div>
<p>{{ $t('message.hello') }}</p>
<p>{{ $t('message.welcome', { name: 'Vue' }) }}</p>
<button>{{ $t('message.button.submit') }}</button>
</div>
</template>
通过 this.$i18n.t() 调用
export default { mounted() { console.log(this.$i18n.t('message.hello')) // 输出当前语言的"你好"或"Hello" } }
通过修改 this.$i18n.locale 实现语言切换:
<template>
<div>
<button @click="changeLang('zh')">中文</button>
<button @click="changeLang('en')">English</button>
</div>
</template>
<script>
export default {
methods: {
changeLang(lang) {
this.$i18n.locale = lang // 切换语言
}
}
}
</script>
持久化语言偏好:结合 localStorage 保存用户选择的语言,初始化时读取:
// 在 src/lang/index.js 中 const i18n = new VueI18n({ locale: localStorage.getItem('lang') || 'zh', // 优先从本地存储读取 // ...其他配置 })
此内容由惯性聚合(RSS阅读器)自动聚合整理,仅供阅读参考。 原文来自 — 版权归原作者所有。