背景 :
先後端開發依賴後端數據, 當前端頁面開發完成 ,後端在沒有提供前端數據的狀況下 ,前端沒法測試,
致使開發效率低 ,速度慢 ,爲了解決這一問題 ,經過Mock模擬生成數據在不改變原有代碼前提下攔截url返回數據。html
開始實驗前端
一、隨機生成長度1~3的數組git
// array數組 var data = Mock.mock({ 'list|1-3': [{// 屬性 list 的值是一個數組,其中含有 1 到 10 個元素 'id|+1': 1, // 屬性 id 是一個自增數,起始值爲 1,每次增 1 'name|1':"吳小明", //字符串 "city": { 'number|1':"03443", 'cityname|1':"北京" } }] })
二、攔截url 返回生成數據
Mock.mock( rurl, template )
記錄數據模板。當攔截到匹配 rurl 的 Ajax 請求時,將根據數據模板 template 生成模擬數據,並做爲響應數據返回。github
Mock.mock( '/user_list', data )
三、建立一個ajax請求ajax
$.get('/user_list',function(response){ console.log("result->"+response); })
四、輸出結果後端
result->{ "list": [ { "id": 1, "name": "吳小明", "city": { "number": "03443", "cityname": "北京" } }, { "id": 2, "name": "吳小明", "city": { "number": "03443", "cityname": "北京" } } ] }
其餘格式數組
// object對象 var data = Mock.mock({ "city|2": { "310000": "上海市", "320000": "江蘇省", "330000": "浙江省", "340000": "安徽省" } })
結果 :工具
result->{ "city": { "310000": "上海市", "320000": "江蘇省" } }
// 生成多數組 var data = Mock.mock({ 'code':0, 'result':{ 'monthAmount|1-5': [{ 'date': '2016-08', 'income|1000-100000':2289, 'expend|1000-100000':2000 }], 'billList|1-10': [{ 'id|+1': 1, 'amount|1000-500000':500000, 'balance|1000-500000':500000, 'type|1-2':1, 'sourceId|1-5':2, 'orderNumber':'45678900443432', 'mchName':'大王雜貨店', 'date':"2017-09-14 16:58:52" }] } })
結果 :測試
result->{ "code": 0, "result": { "monthAmount": [ { "date": "2016-08", "income": 12645, "expend": 56038 }, { "date": "2016-08", "income": 30689, "expend": 46730 } ], "billList": [ { "id": 1, "amount": 191426, "balance": 197800, "type": 2, "sourceId": 2, "orderNumber": "45678900443432", "mchName": "大王雜貨店", "date": "2017-09-14 16:58:52" }, { "id": 2, "amount": 340886, "balance": 432764, "type": 1, "sourceId": 2, "orderNumber": "45678900443432", "mchName": "大王雜貨店", "date": "2017-09-14 16:58:52" }, { "id": 3, "amount": 361772, "balance": 306595, "type": 1, "sourceId": 3, "orderNumber": "45678900443432", "mchName": "大王雜貨店", "date": "2017-09-14 16:58:52" }, { "id": 4, "amount": 360725, "balance": 35917, "type": 1, "sourceId": 3, "orderNumber": "45678900443432", "mchName": "大王雜貨店", "date": "2017-09-14 16:58:52" }, { "id": 5, "amount": 182107, "balance": 413671, "type": 1, "sourceId": 2, "orderNumber": "45678900443432", "mchName": "大王雜貨店", "date": "2017-09-14 16:58:52" }, { "id": 6, "amount": 351296, "balance": 42905, "type": 1, "sourceId": 4, "orderNumber": "45678900443432", "mchName": "大王雜貨店", "date": "2017-09-14 16:58:52" }, { "id": 7, "amount": 457212, "balance": 43885, "type": 1, "sourceId": 3, "orderNumber": "45678900443432", "mchName": "大王雜貨店", "date": "2017-09-14 16:58:52" } ] } }
完整代碼已提交到github ,使用的話能夠直接從github上面下載運行
https://github.com/fozero/front-awesome/tree/master/mockjsurl
mock官方地址: http://mockjs.com/
總結 :
在前端開發中,學會使用一些工具,能極大的提升開發效率 , 減小重複勞動 ,意義重大。
做者:fozero
聲明:原創文章,轉載請註明出處,謝謝!http://www.cnblogs.com/fozero/p/8083331.html 標籤:mock