当前位置:首页 > VUE

vue实现中英切换

2026-01-16 01:34:39VUE

国际化(i18n)方案

Vue 中实现中英切换通常采用 vue-i18n 库,以下是具体实现步骤:

安装依赖:

npm install vue-i18n

配置多语言文件

创建语言资源文件,例如:

// en.json
{
  "welcome": "Welcome",
  "button": {
    "submit": "Submit"
  }
}

// zh-CN.json
{
  "welcome": "欢迎",
  "button": {
    "submit": "提交"
  }
}

初始化 i18n 实例

在 Vue 项目中初始化国际化插件:

import Vue from 'vue'
import VueI18n from 'vue-i18n'

Vue.use(VueI18n)

const messages = {
  en: require('./locales/en.json'),
  'zh-CN': require('./locales/zh-CN.json')
}

const i18n = new VueI18n({
  locale: 'en', // 默认语言
  fallbackLocale: 'en', // 回退语言
  messages
})

export default i18n

在组件中使用

模板中使用 $t 方法:

vue实现中英切换

<template>
  <div>
    <h1>{{ $t('welcome') }}</h1>
    <button>{{ $t('button.submit') }}</button>
  </div>
</template>

脚本中切换语言:

methods: {
  changeLanguage(lang) {
    this.$i18n.locale = lang
  }
}

语言切换组件

实现一个语言切换下拉框:

<select v-model="$i18n.locale">
  <option value="en">English</option>
  <option value="zh-CN">中文</option>
</select>

持久化存储

为保持用户选择的语言,可使用 localStorage:

vue实现中英切换

created() {
  const savedLocale = localStorage.getItem('locale')
  if (savedLocale) {
    this.$i18n.locale = savedLocale
  }
},
watch: {
  '$i18n.locale'(newVal) {
    localStorage.setItem('locale', newVal)
  }
}

动态导入优化

对于大型项目,建议按需加载语言包:

async changeLanguage(lang) {
  const messages = await import(`@/locales/${lang}.json`)
  this.$i18n.setLocaleMessage(lang, messages.default)
  this.$i18n.locale = lang
}

日期时间本地化

处理日期时间格式差异:

import { DateTime } from 'luxon'

const dateFormats = {
  en: {
    short: {
      year: 'numeric', month: 'short', day: 'numeric'
    }
  },
  'zh-CN': {
    short: {
      year: 'numeric', month: 'short', day: 'numeric'
    }
  }
}

const i18n = new VueI18n({
  dateTimeFormats: dateFormats
})

模板中使用:

<span>{{ $d(new Date(), 'short') }}</span>

标签: 中英vue
分享给朋友:

相关文章

vue实现横向导航

vue实现横向导航

vue实现横向导航的方法 使用Flex布局实现横向导航 在Vue中可以通过Flex布局快速实现横向导航。创建一个组件,使用display: flex和flex-direction: row属性使导航项…

vue实现alert

vue实现alert

实现自定义 Alert 组件 在 Vue 中可以通过组件化方式实现自定义 Alert 弹窗。以下是基于 Vue 3 的实现示例: 组件代码 (Alert.vue) <template>…

vue computed 实现

vue computed 实现

computed 的基本用法 在 Vue 中,computed 用于声明计算属性,这些属性基于响应式依赖进行缓存。只有当依赖发生变化时,计算属性才会重新计算。 new Vue({ data: {…

vue 实现直播

vue 实现直播

Vue 实现直播的基本方法 在Vue中实现直播功能,通常需要结合WebRTC、RTMP或HLS等技术。以下是几种常见的实现方式: 使用WebRTC实现实时直播 WebRTC适合低延迟的实时直播场景,…

vue实现抽奖

vue实现抽奖

Vue 实现抽奖功能 基本抽奖逻辑 创建一个Vue组件,包含奖品列表、抽奖按钮和结果显示区域。使用随机数生成器选择奖品。 <template> <div> <…

vue实现画板

vue实现画板

Vue 实现画板功能 在 Vue 中实现画板功能可以通过 HTML5 的 Canvas API 实现。以下是一个完整的实现方案: 创建 Vue 组件 新建一个 Vue 单文件组件(SFC),命名为…