当前位置:首页 > 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 实现适老化样式的关键方法 全局字体与字号调整 通过 CSS 变量或主题配置统一放大基础字号,建议正文不小于 18px,标题更大。在 App.vue 中设置全局样式: :root { --…

vue 动画 实现

vue 动画 实现

vue 动画实现方法 Vue 提供了多种方式实现动画效果,主要包括过渡动画和动态动画两类。 使用 <transition> 组件实现基础过渡 通过 Vue 内置的 <transi…

vue实现图册

vue实现图册

Vue实现图册功能 在Vue中实现图册功能通常涉及图片展示、切换、缩放等交互效果。以下是常见的实现方法和关键代码示例: 基础图册组件结构 使用Vue单文件组件构建基础结构: <templ…

vue 实现脚本

vue 实现脚本

Vue 实现脚本的方法 Vue.js 提供了多种方式来实现脚本功能,包括组件内脚本、混入(Mixins)、插件(Plugins)以及自定义指令等。以下是常见的实现方式: 组件内脚本 在 Vue 单…

vue 实现fadeout

vue 实现fadeout

Vue 实现淡出效果 在 Vue 中实现淡出(fade-out)效果可以通过 CSS 过渡或动画结合 Vue 的动态渲染功能完成。以下是几种常见方法: 使用 Vue 过渡(Transition)组件…

vue实现监听

vue实现监听

监听数据变化 在Vue中,可以通过watch选项或$watch方法监听数据的变化。watch适用于组件选项内声明式监听,$watch适用于动态监听。 // 选项式API export defaul…