在模块test-party
中,我们通过一个简单的例子演示前后端开发的基本流程:
- 实现一个后端API,返回’Hello World’
- 创建一个前端页面,点击按钮,访问后端API,并将返回的’Hello World’显示在页面中
后端代码
1. 添加API路由
src/suite-vendor/test-party/modules/test-party/backend/src/routes.js
- 1// test
- 2{ method: 'post', path: 'kitchen-sink/guide/echo', controller: 'testKitchensinkGuide' },
2. 添加控制器
src/suite-vendor/test-party/modules/test-party/backend/src/controller/kitchen-sink/guide.js
- 1module.exports = app => {
- 2
- 3 class GuideController extends app.Controller {
- 4
- 5 async echo() {
- 6 const message = 'Hello World';
- 7 this.ctx.success(message);
- 8 }
- 9
- 10 }
- 11 return GuideController;
- 12};
src/suite-vendor/test-party/modules/test-party/backend/src/controllers.js
- 1const testKitchensinkGuide = require('./controller/kitchen-sink/guide.js');
- 2
- 3module.exports = app => {
- 4 const controllers = {
- 5 testKitchensinkGuide,
- 6 };
- 7 return controllers;
- 8};
前端代码
1. 添加页面路由
src/suite-vendor/test-party/modules/test-party/front/src/routes.js
- 1function loadKitchenSink(name) {
- 2 return require(`./kitchen-sink/pages/${name}.vue`).default;
- 3}
- 4
- 5export default [
- 6 { path: 'kitchen-sink/guide', component: loadKitchenSink('guide') },
- 7];
2. 添加页面组件
src/suite-vendor/test-party/modules/test-party/front/src/kitchen-sink/pages/guide.vue
- 1<template>
- 2 <eb-page>
- 3 <eb-navbar :title="$text('Guide')" eb-back-link="Back"></eb-navbar>
- 4 <f7-card>
- 5 <f7-card-content>
- 6 <div class="alert-info">{{message}}</div>
- 7 <p>
- 8 <eb-button :onPerform="onPerformClick">{{$text('Click')}}</eb-button>
- 9 </p>
- 10 </f7-card-content>
- 11 </f7-card>
- 12 </eb-page>
- 13</template>
- 14<script>
- 15export default {
- 16 data() {
- 17 return {
- 18 message: null,
- 19 };
- 20 },
- 21 methods: {
- 22 onPerformClick() {
- 23 return this.$api.post('kitchen-sink/guide/echo').then(data => {
- 24 this.message = data;
- 25 });
- 26 },
- 27 },
- 28};
- 29
- 30</script>
- 31<style scoped>
- 32</style>
CabloyJS前端基于VueJS+Framework7,并根据快速开发
的需要,对Framework7的部分组件进行了定制
所有页面组件必须有一个根节点eb-page
。在这里,我们添加了一个按钮。响应按钮点击事件,访问后端API,将返回的数据显示在页面中
效果
打开链接http://localhost:9092/#!/test/party/kitchen-sink/guide,可以查看前后端联动的效果
评论: