vite i18n nuxt国际化

  1. 使用 vue-i18n/i18next 库
    vue-i18n
    官方文档:https://kazupon.github.io/vue-i18n/zh/
    步骤1:安装vue-i18n
npm install vue-i18n@next

步骤2:设置vue-i18n

// src/i18n.ts
import { createI18n } from 'vue-i18n'
import zhCn from 'element-plus/es/locale/lang/zh-cn'; 
import enUs from 'element-plus/es/locale/lang/en';
// 语言资源
const messages = {
  en: {
    message: {
      hello: 'Hello World!',
      welcome: 'Welcome to Vue 3 + i18n',
      ...zhCn,
    }
  },
  zh: {
    message: {
      hello: '你好,世界!',
      welcome: '欢迎使用 Vue 3 + i18n',
      ...enUs,
    }
  }
}

// 创建 i18n 实例
const i18n = createI18n({
  locale: 'en', // 默认语言
  fallbackLocale: 'en', // 回退语言
  messages // 语言消息
})

export default i18n

步骤3:在 Vue 项目中引入 i18n

// src/main.ts
import { createApp } from 'vue'
import App from './App.vue'
import i18n from './i18n' // 引入 i18n 配置

const app = createApp(App)
//全局注册t方法
app.config.globalProperties.t = i18n.global.t 
app.use(i18n) // 将 i18n 实例添加到 Vue 应用中

app.mount('#app')

步骤4:在组件中使用国际化

<template>
  <div>
    <h1>{{ t('message.hello') }}</h1>
    <p>{{ t('message.welcome') }}</p>
  </div>
</template>

步骤5:切换语言

<template>
  <div>
    <h1>{{ t('message.hello') }}</h1>
    <p>{{ t('message.welcome') }}</p>
    <button @click="switchLanguage('en')">English</button>
    <button @click="switchLanguage('zh')">中文</button>
  </div>
</template>

<script>
import { useI18n } from 'vue-i18n'
const { locale  } = useI18n()
const switchLanguage = (lang) => {
  locale.value = lang
}
</script>
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容