当前位置:首页 > 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 方法:

<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:

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实现聊天

Vue实现聊天功能 基础项目结构搭建 使用Vue CLI或Vite创建项目,安装必要依赖如socket.io-client或axios(根据通信方式选择)。核心组件通常包括: ChatWindow…

vue实现多选div

vue实现多选div

实现多选 DIV 的基本思路 在 Vue 中实现多选 DIV 功能,可以通过以下方法实现。主要思路是利用 v-model 绑定选中状态,结合 CSS 类名动态切换样式。 数据准备与模板结构 定义一…

vue怎么实现页面返回

vue怎么实现页面返回

Vue 实现页面返回的方法 在 Vue 中实现页面返回功能,可以通过以下几种方式完成,具体取决于项目使用的路由模式和技术栈。 使用 Vue Router 的编程式导航 通过 this.$router…

vue为啥能实现监听

vue为啥能实现监听

Vue 实现监听的原理 Vue 的监听能力主要基于其响应式系统,该系统通过数据劫持和依赖收集实现。当数据变化时,系统能自动触发视图更新或执行回调函数。 核心机制:Object.definePrope…

vue怎么实现数据检测

vue怎么实现数据检测

Vue 数据检测的实现方式 Vue 通过响应式系统实现数据检测,核心机制基于 Object.defineProperty(Vue 2)或 Proxy(Vue 3)。以下是具体实现方法: 基于 Vu…

vue实现查询替换

vue实现查询替换

Vue 实现查询替换功能 在 Vue 中实现查询替换功能,可以通过数据绑定和字符串操作方法结合实现。以下是具体实现方式: 基础实现 <template> <div>…