vue实现中英切换
Vue 实现中英切换的方法
使用 vue-i18n 插件
安装 vue-i18n 插件:
npm install vue-i18n
在项目中配置 vue-i18n:
import Vue from 'vue'
import VueI18n from 'vue-i18n'
Vue.use(VueI18n)
const messages = {
en: {
message: {
hello: 'Hello'
}
},
zh: {
message: {
hello: '你好'
}
}
}
const i18n = new VueI18n({
locale: 'en', // 默认语言
messages
})
new Vue({
i18n
}).$mount('#app')
在模板中使用:

<template>
<div id="app">
<p>{{ $t('message.hello') }}</p>
<button @click="changeLang('en')">English</button>
<button @click="changeLang('zh')">中文</button>
</div>
</template>
<script>
export default {
methods: {
changeLang(lang) {
this.$i18n.locale = lang
}
}
}
</script>
自定义切换方法
创建语言包文件:
// lang/en.js
export default {
hello: 'Hello'
}
// lang/zh.js
export default {
hello: '你好'
}
在 Vue 组件中实现切换:

import en from './lang/en'
import zh from './lang/zh'
export default {
data() {
return {
currentLang: 'en',
langs: {
en,
zh
}
}
},
methods: {
changeLang(lang) {
this.currentLang = lang
}
},
computed: {
t() {
return this.langs[this.currentLang]
}
}
}
模板中使用:
<template>
<div>
<p>{{ t.hello }}</p>
<button @click="changeLang('en')">English</button>
<button @click="changeLang('zh')">中文</button>
</div>
</template>
持久化语言选择
使用 localStorage 保存语言选择:
methods: {
changeLang(lang) {
this.$i18n.locale = lang
localStorage.setItem('lang', lang)
}
},
created() {
const savedLang = localStorage.getItem('lang')
if (savedLang) {
this.$i18n.locale = savedLang
}
}
动态加载语言包
按需加载语言包减少初始加载体积:
async changeLang(lang) {
const messages = await import(`@/lang/${lang}.js`)
this.$i18n.setLocaleMessage(lang, messages.default)
this.$i18n.locale = lang
}






