上一篇博客我向大家介绍了基于ko-easyui实现的开发模板,博客地址:https://www.cnblogs.com/cqhaibin/p/9825465.html#4095185。但在还遗留三个问题。本篇幅文章就以解决这三问题展开。
一、代理
前后端分离的开发模式,一定会存在前端开发工程,与后端工程不在面一个项目。那就一定需要引用代理来进行统一。否则就会遇到跨域的问题。这个问题使用的webpack的反射代理模块解决,配置代码如下:
devServer:{ contentBase: './dist', port: 9001, proxy:{ '/api/*':{ target: 'http://localhost:80/', //代理的目标服务器 //pathRewrite: {"^/api": ""}, //重写向地址,这里是去年/api前缀,如果没有,则/api/a访问的地址是:http://192.168.0.13:1991/api/a secure: false //是否需要ssl的验证 } } }
上述配置在webpack4.x这后的版本可以正常运行。
二、Mock
Mock我们可以用mockjs来解决,Mockjs的使用还是相当简单。首先使用npm安装mockjs包,然后进行你的数据mockjs即可。简单mockjs代码如下:
import * as mockjs from 'mockjs'; export function deviceMock(){ mockjs.mock('/api/device/index', 'get', ()=>{ let devs = []; devs.push({ShortDevLabel: '001R101', addrName: '入井'}); devs.push({ShortDevLabel: '001R102', addrName: '出井'}); return { IsSuccess: true, Data: devs }; }); }
上述代码Mock了一个/api/device/index的get请求返回数据。但需要注意的是,mockjs的代码需要在整个项目的代码入口处引用。
三、路由
路由我们选择了page.js,因为他更为灵活和方便,且依赖性低。对路由我们要做到路由的变化要更改相应的动态组件变量,否则路由怎么生效呢。所以我们实现的步骤如下:
3.1 入口处调用路由管理模块创建Page对象,并返回关联的ko监控对象
import 'html5-history-api'; import * as page from 'page'; import {RouteManage} from './routeManage'; export class Route{ routeManage:RouteManage; component:KnockoutObservable<any>; page:any; constructor(){ this.component = ko.observable(); this.page = page; } start(){ this.routeManage = new RouteManage(this.page, this.component); page({ hashbang:true }); return this.component; } }
入口处调用代码
//路由 let route = new Route(); let component = route.start(); //测试组件 let rootVm={ $services: createServices(), $route: route, $component: component, /** * 获取全局的弹出窗口 */ getDialogs: function(){ //@ts-ignore let $dialogs = koeasyui.getContextFor(document.getElementById('dialogs')); return $dialogs; } } ko.applyBindings(rootVm, document.getElementById('app'));
从上述代码可以看出引用处,调用了路由管理类的start方法,并返回component这个ko监控对象;然后将处变量注入到app根对象。
3.2 将返回的Ko监控对象与视图中的component指令进行绑定,实现数据与视图的关联
接受上app根对象上的$component这个ko监控对象,然后将此对象与dom进行绑定
html:
<!-- ko if:component() --> <div data-bind="component:component"></div> <!-- /ko—>
javascript:
export class ViewModel{ public component:KnockoutObservable<any>; public routes:any; constructor(params, componentDef, $root){ this.component = $root.$component; } }
3.3 注册路由,并跳转到自定义的默认路由
经过前面一连续的操作,我们的路由与视图已经做好了绑定,现在就需要添加路由和绑定到默认路由了,代码如下:
let $route = <RouteManage>$root.$route.routeManage; $route.addRoute(new RouteInfo('/test', 'test', 'easyui', 'test')); $route.addRoute(new RouteInfo('/bind', 'bind', '列表', 'bind')); this.routes($route.routes); $root.$route.page.redirect('/test');