当前位置:   article > 正文

在vue3中使用vue-i18n多语言配置_vue3 在js中使用 i18n 非setup

vue3 在js中使用 i18n 非setup

1、安装vue-i18n

我目前使用的版本"vue": “^3.2.25”, “vue-i18n”: “^9.1.10”,

pnpm i vue-i18n
  • 1

2、新建中英文对照语言

在这里插入图片描述

//   language/en.js
export default {
  菜单:'menu',
  title:'title'
}
  • 1
  • 2
  • 3
  • 4
  • 5
//  language/zh-cn.js
export default {
  菜单:'菜单',
  title:'标题'
}
  • 1
  • 2
  • 3
  • 4
  • 5
//   language/index.js
import zhCn from "./zh-cn";
import en from "./en";
const language = {
  'zh-CN':zhCn,
  'en-US':en
}

export default language
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

3、在main.js中引入

//  main.js
import { createI18n } from 'vue-i18n'
import language from './language'

const international = createI18n({
  //名字要和上面的一致
  locale:'zh-CN',
  messages:language
})

const app = createApp(App)
// 使用国际化
app.use(international)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

4、切换语言

<script setup>
import { getCurrentInstance } from "vue";
import { useI18n } from 'vue-i18n'

// 切换语言
const { proxy } = getCurrentInstance() as any;
const $t = useI18n()

const changeLanguage = (type: String) => {
  console.log("当前选择的语言:" + type);
  switch (type) {
    case "chinese":
      proxy.$i18n.locale = "zh-CN";
      break;
    case "english":
      proxy.$i18n.locale = "en-US";
      break;
  }
console.log(proxy);
};
</script>


<template>
	<!-- 切换语言 -->
	<h1>{{ $t('title') }}</h1>
	<h1>{{ $t('菜单') }}</h1>
	<button @click="changeLanguage('chinese')">中文</button>
	<button @click="changeLanguage('english')">英文</button>
</template>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30

ok!!!
大功告成了,快去试试吧

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小蓝xlanll/article/detail/439742
推荐阅读
相关标签
  

闽ICP备14008679号