1、mock解決的問題前端
開發時,後端還沒完成數據輸出,前端只好寫靜態模擬數據。數據太長了,將數據寫在js文件裏,完成後挨個改url。某些邏輯複雜的代碼,加入或去除模擬數據時得當心翼翼。想要儘量還原真實的數據,要麼編寫更多代碼,要麼手動修改模擬數據。特殊的格式,例如IP,隨機數,圖片,地址,須要去收集git
2、mock優勢github
//定義數據
const data = Mock.mock({ "data|20": [{ "goodsId|+1": 1, "goodsName": "@ctitle(10)", "goodsTel": /^1(5|3|7|8)[0-9]{9}$/, "goodsAddress": "@county(true)", "goodsLogo": "@Image('200x100', 'EasyMock')", }] }) //模擬數據接口
Mock.mock(/\/shoopList/,"post",function(options){ console.log(options); return data })
// apis/shop.js
const Mock = require("mockjs"); let data = Mock.mock({ "data|50":[ { "shopId|+1": 1, "shopName": "@ctitle(10)", "shopTel": /^1(5|3|7|8)[0-9]{9}$/, "shopAddress": "@county(true)", "shopStar|1-5": "★", "salesVolume|30-1000": 30, "shopLogo": "@Image('100x40','#c33', '#ffffff','小北鼻')", "food|7":[ { "foodName":"@cname(5)", "foodPic":"@Image('100x40','#c33', '#ffffff','小可愛')", "foodPrice|1-100":20, } ] } ] }) let dataList = data.data; function currentPage(page,limit){ var arr = dataList.filter((item,index)=>{ return index<(page*limit) && index>=(page-1)*limit }) return arr; } const getShopPage = (config)=>{ let {page,limit} = pathParams(config.url.split("?")[1]); return { data:currentPage(page,limit), page:Math.ceil(dataList.length/limit) }; } const modifyShop = (config)=>{ let obj = pathParams(config.body); let page = obj.page; delete obj.page; dataList[obj.shopId-1] = {...dataList[obj.shopId],...obj}; console.log(dataList[obj.shopId]) return currentPage(page,8) ; } export default { getShopPage, modifyShop }