最近做了一个新的小项目,需要使用mockjs+axios来模拟后台数据,就来记录一下mockjs 的使用:
1. 安装mockjs和axios
npm install mockjs --save-dev
npm install axios --save
2.在项目里新建一个mock的文件夹,将mock的请求接口放在此文件夹里
其中index.js里面的代码如下:
// index.js import Mock from "mockjs"; Mock.mobile_prefix = [ "134", "135", "136", "137", "138", "139", "150", "151", "152", "157", "158", "159", "130", "131", "132", "155", "156", "133", "153" ]; Mock.bank_prefix = [ "4367", "6227", "6228", "9559", "6222", "9558", "6216", "4563", "6013", "6221", "6210", "6014", "5218", "6282", "3568", "6226", "4218", "6229", "4864", "6029", "9988" ]; Mock.numeric = "0123456789"; let pagesize = 0; const chartData = () => { // mock随机数据 const Random = Mock.Random; let dataArr = []; for (let i = 1; i <= pagesize; i++) { let newData = { id: i, user_name: Random.cname(), // 随机生成中文姓名 user_bank: Mock.getBank(), // 随机生成银行卡卡号(统一19位) phone: Mock.getMobile(), //手机号 status: "已转账" }; dataArr.push(newData); } return dataArr; }; Mock.random = (len, list) => { if (len <= 1) { len = 1; } var s = ""; var n = list.length; if (typeof list === "string") { while (len-- > 0) { s += list.charAt(Math.random() * n); } } else if (list instanceof Array) { while (len-- > 0) { s += list[Math.floor(Math.random() * n)]; } } return s; }; Mock.getMobile = () => { return Mock.random(1, Mock.mobile_prefix) + Mock.random(8, Mock.numeric); }; Mock.getBank = () => { return Mock.random(1, Mock.bank_prefix) + Mock.random(15, Mock.numeric); }; // Mock.mock(url,method,data) 三个参数对应 api地址、请求方式、请求参数 Mock.mock("/getData", "post", data => { pagesize = JSON.parse(data.body).pagesize; return { success: "true", code: "200", data: chartData() }; });
3. 将mock/index.js引入到项目里的main.js中
require("./mock/mock");
4. 在组件中调用接口获取模拟的数据
let params = { pagesize: this.pagesize }; let count = this.total % this.pagesize; let page = parseInt(this.total / this.pagesize); if (this.current > page) { params.pagesize = count; } axios.post("/getData", params).then(res => { this.tableData = res.data.data; });