JavaScript代码
- //定义/mock/index.js
- import Mock from 'mockjs'
- Mock.mock("/api/login", {
- code: 200,
- msg: "登陆成功",
- user: {
- name: "zeng8",
- score: 2048,
- rank: 10
- },
- token: "kjkjalsdiiuioayeuryqowierqiwerqowiery"
- })
- // url可以使用正则匹配
- // 拦截get请求,返回评论数据
- Mock.mock(/\/api\/feed/, "get", function(config) {
- //console.log("config" , config );
- //通过config可以获取到前端发给服务器的数据
- var po = config.url.indexOf("?"); //获取问号的位置
- if (po != -1) {
- var query = config.url.slice(po + 1); //获取到查询参数current=4转换为{current: 4}
- var arr = query.split("&"); //按&分割为数组
- var search = {}; //定义个对象
- arr.forEach(item => {
- var temp = item.split("="); //把数组每个元素按等于分割[current,4]
- search[temp[0]] = temp[1]; //search[ "current"] =4
- })
- }
- // 返回一个随机数据
- return Mock.mock({
- "code": 0,
- "data|4": [{
- id: "@id",
- msg: "@cparagraph(2,3)", //段落2-3行
- name: "@cname", //随机中文名
- date: "@datetime" //随机日期
- }],
- "pagnation": {
- "total|10-25": 1,
- "size": 4,
- "pageTotal|4-10": 1,
- "current": search.current,
- }
- })
- })
- Mock.mock("/api/test", Mock.mock({
- name: "@cname", //随机中文名
- "age|100-200": 1, //100-200的随机数
- "price|10-50.2-5": 1, //10-50随机数 小数点2-5位
- "live|1-2": true, //随机true或false
- "start|1-5": "⭐", //把字符串重复1-5次
- "friend|2": ["小红", "小明", "小刚", "小白", "小蓝"], //1是挑一个大于1是重复n次
- "props|1-3": {
- name: "mm",
- age: 22,
- leg: 2,
- job: "web",
- eye: 2
- },
- "tel": /13\d{9}/,
- "des": function() {
- return `大家好,我的名字是${this.name},今年${this.age}岁`
- },
- "data|10": [{
- "id|+1": 1024,
- "ID": "@id",
- date: "@date",
- time: "@time",
- datetime: "@datetime",
- name: "@cname",
- pic: "@dataImage('200x100')",
- description: "@cparagraph(1,3)",
- title: "@ctitle(8,12)",
- url: /http:\/\/www\.[a-z]{2,8}\.(com|cn|org)/,
- email: /[4-8]@\.(126|qq|163)\.(com|cn|org)/,
- address: "@county(true)", //省市区地址
- }]
- }))