vue3+ts使用vue-i18n

vue3+ts使用vue-i18n

1、安装插件

复制代码
npm install --save vue-i18n

yarn add vue-i18n

2、配置文件

locale/index.ts

ts 复制代码
import { createI18n } from 'vue-i18n'
import zhCN from './lang/zh-CN'
import enUS from './lang/en-US'

export const LOCALE_OPTIONS = [
  { label: '中文', value: 'zh-CN' },
  { label: 'English', value: 'en-US' },
];
const defaultLocale = localStorage.getItem('locale') || 'zh-CN';
const i18n = createI18n({
  locale: defaultLocale,
  legacy: false, // 解决控制台报错 Uncaught SyntaxError: Not available in legacy mode
  messages: {
    'zh-CN': zhCN,
    'en-US': enUS,
  }
})

export default i18n

locale/lang/zh-CN.ts

ts 复制代码
export default {
  'menu.list': '列表',
  'menu.message': '信息',
}

locale/lang/en-US.ts

ts 复制代码
export default {
  'menu.list': 'List',
  'menu.message': 'Message'
}

3、在main.ts引入

main.ts

ts 复制代码
import i18n from './locale'

// 在app.mount之前
app.use(i18n)

4、在页面中使用

html 复制代码
<template>
  <div>
    <ul>
      <li
        v-for="(item, index) in locales"
        :key="index"
        @click="changeLocale(item.value)"
      >{{ item.label }}</li>
    </ul>
    <p>{{ $t('menu.list') }}</p>
    <p>{{ $t('menu.message') }}</p>
    <p></p>
  </div>
</template>

<script setup lang="ts">
import { LOCALE_OPTIONS } from '@/locale'
import { useI18n } from 'vue-i18n'

const locales = [
  ...LOCALE_OPTIONS
]

const i18n = useI18n()
function changeLocale(value: string) {
  i18n.locale.value = value;
  localStorage.setItem('locale', value)
}
</script>

5、解决控制台报错/警告

5.1、需要配置全局变量

  • 警告信息

    You are running the esm-bundler build of vue-i18n. It is recommended to configure your bundler to explicitly replace feature flag globals with boolean literals to get proper tree-shaking in the final bundle.

  • 解决方案

vue.config.js

js 复制代码
const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
  chainWebpack: (config) => {
    config.resolve.alias
    .set('vue-i18n', 'vue-i18n/dist/vue-i18n.cjs.js')
  },
})

5.2、遗留模式报错

  • 报错信息

    Uncaught SyntaxError: Not available in legacy mode

  • 解决方案

ts 复制代码
import { createI18n } from 'vue-i18n'

const i18n = createI18n({
  ...
  legacy: false, // 解决控制台报错 Uncaught SyntaxError: Not available in legacy mode
  ...
})
相关推荐
筱歌儿4 小时前
TinyMCE-----word表格本地图片转base64并上传
前端·word
研☆香4 小时前
html css js文件开发规范
javascript·css·html
0思必得04 小时前
[Web自动化] Selenium简单使用
前端·python·selenium·自动化·web自动化
2301_818732064 小时前
下载nvm后,通过nvm无法下载node,有文件夹但是为空 全局cmd,查不到node和npm 已解决
前端·npm·node.js
赵民勇4 小时前
JavaScript中的this详解(ES5/ES6)
前端·javascript·es6
hhcccchh4 小时前
学习vue第九天 计算属性与侦听器
前端·vue.js·学习
wayne2144 小时前
React Native 状态管理方案全梳理:Redux、Zustand、React Query 如何选
javascript·react native·react.js
Irene19914 小时前
Vue 3 中,defineComponent 提供了更好的 TypeScript 类型推断
vue.js·typescript·definecomponent
我的golang之路果然有问题4 小时前
Mac 上的 Vue 安装和配置记录
前端·javascript·vue.js·笔记·macos
代码游侠4 小时前
应用——Linux FrameBuffer图形显示与多线程消息系统项目
linux·运维·服务器·开发语言·前端·算法