分类
解决方案

国际化解决方案(vue)

目录

  1. 国际化自定义配置
  2. 项目中使用需要注意的地方
  3. 国际化过程中节约时间的小插件
  4. 组件库的国际化

国际化配置

i18n下载

npm i vue-i18n

引入

main.js文件配置

// main.js
import Vue from 'vue';
import App from './App.vue';
import router from './router';
import store from './store';
// 国际化
import i18n from './i18n';
// 启动程序
import { created } from './core/bootstrap';

new Vue({
  router,
  store,
  created,
  i18n,
  render: h => h(App),
}).$mount('#app');

i18n目录情况

./src/i18n/
├── index.js
└── lang
    ├── README.md
    ├── en-GB                                # 英式英文 文件夹
    │   ├── business
    │   ├── common
    │   │   └── index.js                   # 通用信息
    │   └── pages                           # 项目页面标签
    │       ├── create.js                   # 新建流程页面
    │       ├── login.js                    # 登录页面
    │       ├── todo.js                     # 待办流程页面
    │       └── view.js                     # 我的申请页面
    ├── en-US                                # 美式英文 文件夹
    │   ├── business
    │   ├── common
    │   │   └── index.js
    │   └── pages
    │       ├── create.js
    │       ├── login.js
    │       ├── todo.js
    │       └── view.js
    └── zh-CN                               # 简体中文 文件夹
        ├── business
        ├── common
        │   └── index.js
        └── pages
            ├── create.js
            ├── login.js
            ├── todo.js
            └── view.js

i18n文件夹下的index.js文件配置国际化详细信息

import Vue from 'vue';
import VueI18n from 'vue-i18n';

import zhCN from './lang/zh-CN';
import enUS from './lang/en-US';
import enGB from './lang/en-GB';

Vue.use(VueI18n);

const messages = {
  'zh-CN': zhCN,
  'en-US': enUS,
  'en-GB': enGB,
};
export const defaultLang = 'zh-CN';
const i18n = new VueI18n({
  // 当前语言,从缓存中读取
  locale: defaultLang,
  // 回退语言-当找不到时,使用回退语言
  // fallbackLocale: defaultLang,
  messages,
});

export default i18n;

function setI18nLanguage(lang) {
  i18n.locale = lang;
  document.querySelector('html').setAttribute('lang', lang.toLowerCase());
  return lang;
}

export function loadLanguageAsync(lang = defaultLang) {
  return new Promise((resolve) => {
    // 缓存语言设置
    if (i18n.locale !== lang) {
      return resolve(setI18nLanguage(lang));
    }
    return resolve(lang);
  });
}

i18n->lang->en-GB->index.js

import login from './login';
import create from './create';
import personCenter from './personCenter';

export default {
  login,
  create,
  personCenter,
};

i18n->lang->en-GB->login.js

export default {
  title: 'welcome login BPM system',
  bt: 'Login',
  placeholder: {
    username: 'please input user name',
    password: 'please input password',
  },
  message: {
    username: 'please input user name',
    password: 'please input password',
  },
  error: 'login fail',
};

流程图-执行流程

qi ye wei xin jie tu 16056018244734 - 国际化解决方案(vue)

启动事件(core => bootstrap.js)

import store from '@/store/';
import auth from '@/utils/auth';
// 应用程序事件处理
export function created() {
  // 从本地存储中恢复语言设置
  store.dispatch('system/app/setLang', auth.getLocal());
}

获取本地语言函数(utils=>auth.js)

export default {
  /**
   * 获取当前语言
   */
  getLocal() {
    return localStorage.local || 'zh-CN';
  },
  /**
   * 设置语言
   */
  setLocal(local) {
    if (localStorage.local !== local) {
      localStorage.local = local;
    }
  },
};

执行国际化函数(store=>system=>app.js)

import {
  // i18n
  APP_LANGUAGE,
} from '@/store/mutation-types';
import auth from '@/utils/auth';
import { loadLanguageAsync } from '@/i18n';
const app = {
  namespaced: true,
  state: {
    // 切换语言
    lang: 'zh-CN',
  },
  mutations: {
    /**
     * 设置语言
     * @param {*} state
     * @param {*} lang
     */
    [APP_LANGUAGE](state, lang) {
      state.lang = lang;
      auth.setLocal(lang);
    },
  },
  actions: {
    setLang({ commit }, lang) {
      return new Promise((resolve, reject) => {
        commit(APP_LANGUAGE, lang);
        loadLanguageAsync(lang).then(() => {
          resolve();
        }).catch((e) => {
          reject(e);
        });
      });
    },
  },
};

export default app;

语言配置名称(store=>mutation-types.js)

export const APP_LANGUAGE = 'app_language';

在项目中进行语言切换

this.$store.dispatch('system/app/setLang', val);

项目中使用需要注意的地方

浏览页标题

某个路由

import loaded from '@/utils/util.import';

export default [
  // 默认页面
  {
    path: '/home',
    name: 'home',
    meta: {
      title: '主页',
      dataKey: 'common.home',// 若使用国际化用这个字段
      tabId: 'home',
      icon: 'home',
      closable: false,
    },
    component: loaded('Home'),
  },
  // 刷新页面 必须保留
  {
    path: '/refresh',
    hidden: true,
    component: loaded('system/function/refresh'),
  },
];

路由拦截函数

import i18n from '@/i18n';
export function routerAfterEachFunc(to) {
  util.title(i18n.t(to.meta.dataKey));
}

一般表格表头-可以放在计算属性中

computed: {
    columns() {
      const columns = [
        {
          title: this.$t('pages.create.columns.sn'),
          align: 'center',
          customRender: (text, record, index) => (this.pageNum - 1) * this.pageSize + index + 1,
        },
        {
          title: this.$t('pages.create.columns.subject'),
          dataIndex: 'subject',
        },
        {
          title: this.$t('pages.create.columns.name'),
          scopedSlots: { customRender: 'lineEllipsis' },
          dataIndex: 'processNameCn',
        },
        {
          title: this.$t('pages.create.columns.createTime'),
          dataIndex: 'createTime',
        },
        {
          title: this.$t('pages.create.columns.action'),
          key: 'action',
          width: 100,
          scopedSlots: { customRender: 'action' },
        },
      ];
      return columns;
    },
  },

2121-04-09更新

columns还是可以放在data中,但是计算属性进行变更

langColumns() {
      this.columns.forEach((item) => {
        item.title = this.$t(`columns.${item.dataIndex}`);
      });
      return this.columns;
    },

动态列表格表头-使用slot

data() {
    return {
        columns: [{
            slots: { title: 'noTitle' },
            dataIndex: 'no',
        }]
    }
}
<a-table :columns="columns">
    <span slot="noTitle">{{$t('columns.sn')}}</span>
</a-table>

国际化过程中节约时间的小插件

流程如下

vscode搜索中文:(.[\u4E00-\u9FA5]+)|([\u4E00-\u9FA5]+.)

qi ye wei xin jie tu a206e6d2cc1342e0b98fc6891bef73bf 569x1024 - 国际化解决方案(vue)

从vscode中找出所有含有汉字的代码->用小插件找到去重的汉字列表给专业人员翻译->开发人员自顾自的编写i18n文件->专业人员翻译好了,给出一个汉字英文对照表->使用小插件把中文i18n文件和汉字英文对照表放上去生成英文i18n文件->复制粘贴完成

guo ji hua xiao cha jian 1 1 - 国际化解决方案(vue)
guo ji hua xiao cha jian 2 - 国际化解决方案(vue)

小插件地址

https://github.com/zhuishao/i18n-plugin-hanzi

组件库的国际化

需求:没用国际化的项目默认显示中文,有国际的的项目使用该组件可配置vue-i18n国际化。

  1. 将https://github.com/zhuishao/ec-zs-components下的src目录复制到组件库中
  2. 在有语言的组件中加入mixins: [Locale], import Locale from ‘ec-zs-components/src/mixins/locale’,通过t(xx.xx.xx)使用
  3. ec-zs-components的引用其实是加了别名alias在vue.config.js中加入
 configureWebpack: {
        resolve: {
            alias: {
                'ec-zs-components': path.resolve(__dirname, './'),
            },
            extensions: ['.js', '.vue', '.json'],
        }
    },
  1. 向外发布的时候需要将语言包暴露出去以供使用在package的script中加入构建命令
"scripts": {
    "lib": "vue-cli-service build --target lib --name ec-zs-components --dest lib --entry packages/index.js && babel src/locale/lang --out-dir lib"
  },

在命令行执行babel命令需要加入babel-cli依赖

使用这个组件库并与i18n产生链接

在main.js国际化配置的基础上引入插件

import i18n from './i18n';
import EcZsComponent from 'ec-zs-components';
import 'ec-zs-components/lib/ec-zs-components.css';
Vue.use(EcZsComponent, {
  i18n: (key, value) => i18n.t(key, value)
});

由zhuishao

github:https://github.com/zhuishao/

“国际化解决方案(vue)”上的8条回复

发表评论

电子邮件地址不会被公开。 必填项已用*标注