vue2 项目实例 国际化(五)

1. 安装依赖

首先安装适合 Vue2 的 vue-i18n 版本(注意:Vue2 需使用 vue-i18n@8.x,Vue3 则用 vue-i18n@9+
 
 
npm install vue-i18n@8 --save
# 或
yarn add vue-i18n@8

 

2. 配置国际化文件

在项目中创建语言包目录(例如 src/lang),并添加不同语言的配置文件:

src/lang/en.js(英文)

 

export default {
  message: {
    hello: 'Hello',
    welcome: 'Welcome to {name}', // 支持变量
    button: {
      submit: 'Submit',
      cancel: 'Cancel'
    }
  }
}

src/lang/zh.js(中文)

export default {
  message: {
    hello: '你好',
    welcome: '欢迎来到 {name}',
    button: {
      submit: '提交',
      cancel: '取消'
    }
  }
}

 

3. 初始化 i18n 实例

创建 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

4. 在 Vue 实例中引入

在 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)
})

 

5. 在组件中使用

模板中使用

  • 基础用法:$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"
  }
}

6. 切换语言

通过修改 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>

 

7. 进阶配置

  • 持久化语言偏好:结合 localStorage 保存用户选择的语言,初始化时读取:

 

// 在 src/lang/index.js 中
const i18n = new VueI18n({
  locale: localStorage.getItem('lang') || 'zh', // 优先从本地存储读取
  // ...其他配置
})

 

 

 

 

 
 
 
 
 
 
 
 
 
 
 

posted on 2025-09-28 16:25  Mc525  阅读(28)  评论(0)    收藏  举报

导航