【vue 配置国际化语言】

项目演示

代码

官网 :https://kazupon.github.io/vue-i18n/

//语言
import {
    
     createI18n } from 'vue-i18n'		//引入vue-i18n组件
import store from "@/store";
import ZH from './zh'  // 引入中文文件
import EN from './en'   // 引入英文文件
// import { 引入的组件 export 出来的 变量} from 'vue-i18n'
  //注册i8n实例并引入语言文件
 const i18n = createI18n({
    
    
    locale: store.getters.locales,		//默认显示的语言 
    legacy: false, // composition AP
    globalInjection: true, //全局生效$
      messages: {
    
    
        'zh-cn':ZH,	//引入语言文件
        'en':EN 
      }
  })


  /**
   * @description:  动态加载 语言包
   * @param {*} routers 菜单列表
   * @return {*} 
   */  
  export const mergeLocaleMessages=(routers)=>{
    
    
    const tree = treeToArr(routers);
    if(tree.length){
    
    
      let cn=tree[0]
      let en=tree[1]
        i18n.global.mergeLocaleMessage("zh-cn",{
    
    
          'menu':{
    
    
            ...cn
          }
        })
        i18n.global.mergeLocaleMessage("en",{
    
    
          "menu":{
    
    
            ...en
          }
        })
    }
} 

/**
 * @description:  递归处理菜单
 * @param {*} arr
 * @param {*} cn
 * @param {*} en
 * @return {*}
 */
const treeToArr=(arr,cn={
     
     },en={
     
     })=>{
    
    
  for(let i=0;i<arr.length;i++){
    
    
    cn[arr[i].path]=arr[i].cn
    en[arr[i].path]=arr[i].en
    if(arr[i].children && arr[i].children.length){
    
    
      treeToArr(arr[i].children,cn,en)    
  }
  }
  return [cn,en]
}
  export default i18n; //将i18n暴露出去,在main.js中引入挂载

zh.js 中文语言包:

// 中文语言包:
export default {
    
    
  menu: {
    
    
      name: "首页",
    },
    message:{
    
    
      Primary:"原色",
      Success:"成功",
      Info:"信息",
      Warning:"警告",
      Danger:"微信",
    },
    language:{
    
    
      tips:"项目只做了菜单的国际化处理,其他页面和功能需要你自己来处理",
      SelectLanguage:"选择语言"
    }
  };

en.js 英文语言包:

// 中文语言包:
export default{
    
    
  menu: {
    
    
    name: "home",
  },
  message:{
    
    
    Primary:"Primary",
    Success:"Success",
    Info:"Info",
    Warning:"Warning",
    Danger:"Danger",
  },
  language:{
    
    
    tips:"The project only handles the internationalization of menus, and other pages and functions need to be handled by yourself",
    SelectLanguage:"Select language"
  }
}

使用方法


<div class="padding-2x flex space-between ">
     <a-button type="primary">{
    
    {
    
    $t('message.Primary')}}</a-button>
     <a-button type="success">{
    
    {
    
    $t('message.Success')}}</a-button>
      <a-button type="info">{
    
    {
    
    $t('message.Info')}}</a-button>
     <a-button type="warning">{
    
    {
    
    $t('message.Warning')}}</a-button>
      <a-button type="danger">{
    
    {
    
    $t('message.Danger')}}</a-button>
</div>

猜你喜欢

转载自blog.csdn.net/qq_44795810/article/details/128657629