2021-12-29

一# vue3.0怎么使用引用vue-i18n

package.json需要插件各版本配置

"dependencies": {
    "vue": "^3.2.25",
    "vue-i18n": "^9.1.6",
  },
  "devDependencies": {
    "@vitejs/plugin-vue": "^2.0.0",
    "vite": "^2.7.2",
    "vite-plugin-compression": "^0.3.3",
    "vite-plugin-style-import": "^1.4.1"
  }

在src中創(chuàng)建lang文件夾,lang文件夾中創(chuàng)建zh.js,en.js,index.js

//index.js頁面
import { createI18n } from 'vue-i18n' //引入vue-i18n組件
import zh from './zh.js'//中文
import za from './en.js'//英文
// const language = (
//   (navigator.language ? navigator.language : navigator.userLanguage) || "zh"
// ).toLowerCase();
const language = "zh"
const i18n = createI18n({
  fallbackLocale: 'ch',
  globalInjection: true,
  legacy: false, // you must specify 'legacy: false' option
  locale: language,
  messages: {
    zh,    //引入語言文件
    en
  }
});
export default i18n
//en.js頁面
export default {
  message: {
    Home: 'Home',
    About: 'About',
    productService: 'productService',
    cases: 'cases',
    news: 'news',
    contactUs: 'contactUs',
  },
}
//zh.js頁面
export default {
  message: {
    Home: '首頁',
    About: '關于我們',
    productService: '產(chǎn)品服務',
    cases: '行業(yè)解決方案',
    news: '新聞動態(tài)',
    contactUs: '聯(lián)系我們',
  },
}

在main.js中引入I18n 掛載

// 語言切換
import I18n from "@/lang/index"; //引入i18n組件
const app = createApp(App)
app.use(I18n).mount('#app')

在頁面中使用

<template>
  <div>
    <div @click="handleSetLanguage('zh')">
      中文
    </div>
    <div @click="handleSetLanguage('za')">
      English
    </div>
    {{$t(`message.Home`)}}//頁面使用
  </div>
</template>
<script>
import {  getCurrentInstance } from "vue";
import { useI18n } from 'vue-i18n'//要在js中使用國際化
export default {
  setup () {
    const { proxy } = getCurrentInstance();//要在js中修改
    const { t } = useI18n()//要在js中使用國際化
    // 語言切換事件:
    const handleSetLanguage = (lang) => {
      console.log(t('message.Home'))//要在js中使用國際化
      proxy.$i18n.locale = lang;//要在js中修改
    };
    return {
       handleSetLanguage
    }
  }
};
</script>

第二次寫簡書不喜勿噴!?。?!

最后編輯于
?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容