Mockjs模拟数据,实现增删改查

Mockjs模拟数据,实现增删改查。

1、安装Mockjs

npm install mockjs --save-dev

因为生产环境用的是正式接口,安装在开发依赖上可以减小包的大小。

2、生成数据初始列表

import Mock from 'mockjs';
const count = 25;
// 处理解析url
const splitParams = url => {
  const search = url.split('?')[1]
  if (!search) {
    return {}
  }
  return JSON.parse('{"' + decodeURIComponent(search).replace(/"/g, '\\"').replace(/&/g, '","').replace(/=/g, '":"') + '"}')
}
// 生成数据列表
const generateList = () => {
  const tempList = [];
  for (let i = 0; i < count; i++) {
    const listItem = Mock.mock({
      'id': '@id',
      'name': '@cname',
      "date": "@date()",//随机生成日期
      'Address': '@county(true)', // 生成省 市 县组成的地址
      'Email': '@email',//生成邮箱
      "avatar": "@image('200x200','red','#fff','avatar')",//生成图片
      // "mark": Random.cparagraph(0, 5),
      "description": "@cparagraph()",//描述中文
    });
    tempList.push(listItem);
  }
  return tempList;
}
let mockList = generateList();

3、基于mockList,获取数据列表

// 获取数据列表
  static async getMockUserlist (ctx, next) {
    const fetchUrl = ctx.request.url;
    const { page = 1, pageSize = 10, key = '' } = splitParams(fetchUrl);
    const tempPageList = key ? mockList.filter(u => u.name.indexOf(key) >= 0 || u.Address.indexOf(key) >= 0) : mockList;
    const pageList = tempPageList.filter((item, index) => index < Number(pageSize) * Number(page) && index >= Number(pageSize) * (Number(page) - 1));
    ctx.state = 200;
    ctx.body = {
      code: '000000',
      message: 'success',
      data: Object.assign({}, { list: pageList, page: Number(page), pageSize: Number(pageSize), total: mockList.length })
    };
  }

4、基于mockList,添加或更新用户信息

 // 添加或更新用户信息
  static async addMockUser (ctx, next) {
    const fetchUrl = ctx.request.url;
    const { name, date, Address, Email, description, id = '' } = splitParams(fetchUrl);
    if (id) {
      mockList.some(u => {
        if (u.id === id) {
          u.name = name;
          u.date = date;
          u.Address = Address;
          u.Email = Email;
          u.description = description;
          return true
        }
      });
    } else {
      const listItem = {
        id: Mock.Random.id(),
        name: name,
        date: date,
        Address: Address,
        Email: Email,
        avatar: Mock.Random.image('200x200', 'red', '#fff', 'avatar'),
        description: description
      };
      mockList.push(listItem);
    }
    ctx.state = 200;
    ctx.body = {
      code: '000000',
      message: 'success',
      data: id ? '编辑成功' : '添加成功'
    };
  }

5、基于mockList,删除用户

 // 删除用户
  static async deleteMockUser (ctx, next) {
    const fetchUrl = ctx.request.url;
    const { id } = splitParams(fetchUrl);
    mockList = mockList.filter(u => u.id !== id);
    ctx.state = 200;
    ctx.body = {
      code: '000000',
      message: 'success',
      data: '删除成功'
    };
  }

参考文档:

https://www.jianshu.com/p/1f6a3180051b

随笔小结,不喜勿喷,谢谢。

你可能感兴趣的:(Mockjs)