CabloyJS的业务模块不仅包含后端逻辑,也包含前端页面。为了提升业务模块的开发效率和灵活性,不仅在后端提供了参数配置国际化特性,在前端也提供了相应的特性,而且也支持项目级别的覆盖

在这里,我们实现一个虚拟的需求:

  1. message参数放到前端配置
  2. 前端再定义一个参数markCount,表示感叹号的个数
  3. 前端将这两个参数传入后端,后端进行组合,并将结果返回
  4. 前端显示返回的结果

参数配置

1. 定义参数

src/suite-vendor/test-party/modules/test-party/front/src/config/config.js

  1. 1export default {
  2. 2 message: 'Hello World',
  3. 3 markCount: 2,
  4. 4};

2. 使用参数

src/suite-vendor/test-party/modules/test-party/front/src/kitchen-sink/pages/guide.vue

  1. 1onPerformClick4() {
  2. 2 const params = {
  3. 3 message: this.$config.message,
  4. 4 markCount: this.$config.markCount,
  5. 5 };
  6. 6 return this.$api.post('kitchen-sink/guide/echo4', params).then(data => {
  7. 7 this.message4 = data;
  8. 8 });
  9. 9},

3. 后端逻辑

src/suite-vendor/test-party/modules/test-party/backend/src/controller/kitchen-sink/guide.js

  1. 1async echo4() {
  2. 2 const { message, markCount } = this.ctx.request.body;
  3. 3 const res = `${message}${new Array(markCount + 1).join('!')}`;
  4. 4 this.ctx.success(res);
  5. 5}

4. 覆盖参数

使用项目级别的参数覆盖模块级别的参数,从而将Hello World改为Hello World!,将markCount2改为3

src/front/config/config.{scene}.js

  1. 1export default{
  2. 2 modules: {
  3. 3 'test-party': {
  4. 4 message: 'Hello World!',
  5. 5 markCount: 3,
  6. 6 },
  7. 7 },
  8. 8};

国际化

1. 定义语言资源

CabloyJS默认语言是en-us,如果需要支持中文,就需要添加zh-cn资源文件

src/suite-vendor/test-party/modules/test-party/front/src/config/locale/zh-cn.js

  1. 1export default {
  2. 2 'Hello World': '世界,您好',
  3. 3};

2. 使用语言资源

CabloyJS通过方法$text根据客户端的locale配置动态使用相应的语言资源

src/suite-vendor/test-party/modules/test-party/front/src/kitchen-sink/pages/guide.vue

  1. 1onPerformClick5() {
  2. 2 const params = {
  3. 3 message: this.$text('Hello World'),
  4. 4 markCount: this.$config.markCount,
  5. 5 };
  6. 6 return this.$api.post('kitchen-sink/guide/echo4', params).then(data => {
  7. 7 this.message4 = data;
  8. 8 });
  9. 9},

3. 覆盖语言资源

使用项目级别的语言资源覆盖模块级别的语言资源,从而将世界,您好改为您好,世界

src/front/config/locale/zh-cn.js

  1. 1export default {
  2. 2 'Hello World': '您好,世界',
  3. 3};

4. 更多的语言资源

同样,我们也可以把测试页面的标题按钮进行国际化处理

src/suite-vendor/test-party/modules/test-party/front/src/config/locale/zh-cn.js

  1. 1export default {
  2. 2 Guide: '指南',
  3. 3 Click: '点击',
  4. 4};

src/suite-vendor/test-party/modules/test-party/front/src/kitchen-sink/pages/guide.vue

  1. 1<template>
  2. 2 <eb-page>
  3. 3 <eb-navbar :title="$text('Guide')" eb-back-link="Back"></eb-navbar>
  4. 4 ...
  5. 5 <eb-button :onPerform="onPerformClick">{{$text('Click')}}</eb-button>
  6. 6 ...
  7. 7 </eb-page>
  8. 8</template>