当前位置:   article > 正文

Vue3中使用vue-i18n实现多语言切换_vue3 多语言

vue3 多语言

1、安装插件【注意Vue3使用9版本,Vue2用的是8版本】

npm install vue-i18n@next 或者 yarn add vue-i18n@next

2、在src在创建lang文件夹,并创建index.js、i18n.js、和 翻译的内容文件

 3、写入翻译内容,举个例子:英文(en)、中文简体(zhCN)、中文繁体(zhTN)

  1. const zhCN = {
  2. messages: {
  3. "upload": "上传"
  4. }
  5. }
  6. export default zhCN

3、编写index.js文件,导出所有翻译内容

  1. import en from './en'
  2. import zhCN from './zh-CN'
  3. import zhCT from './zh-CT'
  4. export default {
  5. en, zhCN, zhCT
  6. }

4、编写i18n.js文件

  1. import { createApp } from 'vue'
  2. import App from '../App.vue'
  3. import { createI18n } from 'vue-i18n'
  4. import messages from './index'
  5. const app = createApp(App)
  6. const i18n = createI18n({
  7. legacy: false, //处理报错Uncaught (in promise) SyntaxError: Not available in legacy mode (at message-compiler.esm-bundler.js:54:19)
  8. locale: localStorage.getItem('lang') || "zhCN", // 注意locale属性~~~~~~~~!
  9. messages
  10. })
  11. export default function (app) {
  12. app.use(i18n)
  13. }

5、在main.js中挂载

 至此,就可以使用按需显示语种了。

那么,当我们去改变locale的值为对应的语种时就可以做到多语言切换了~

  1. <template>
  2. <!-- 国际化页面 -->
  3. <div>
  4. <span>通过切换语言按钮,来改变当前内容的语言</span>
  5. <el-button type="primary" @click="changeLang('en')">英文</el-button>
  6. <el-button type="primary" @click="changeLang('zhCT')">中文繁体</el-button>
  7. <div>
  8. <span>{{ $t("messages.upload") }}</span>
  9. </div>
  10. </div>
  11. </template>
  12. <script setup>
  13. import { useI18n } from "vue-i18n";
  14. const { locale } = useI18n();
  15. const changeLang = (val) => {
  16. locale.value = val;
  17. localStorage.setItem("lang", val);
  18. };
  19. </script>
  20. <style scoped lang='less'>
  21. </style>

多语言

  • 在vue3 template中使用多语言
<span>{{ $t("messages.upload") }}</span>
  • 在vue3 template中数据绑定使用多语言 
 <el-input type="text" :placeholder="$t('messages.placeholderTips')" />
  • 在vue3 setup语法糖中使用多语言:
  1. import { useI18n } from "vue-i18n";
  2. const { t } = useI18n();
  3. console.log('t("messages.home")', t("messages.home"))
  • 在vue3 中路由里使用多语言(面包屑同理)

    <template #title>{{ $t(item.title) }}</template>

 插件官网:Getting started | Vue I18n 

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

闽ICP备14008679号