现有项目引入mock数据方案

85 阅读1分钟

背景:后端接口没有开发完,前端工作需要继续,这个时候就需要前端自己去造数据了,但是写静态数据在页面中,又不是很友好,这个时候就需要一个mock方案来解耦前端的假数据

引入方式:

  1. 在项目的package.json文件scripts字段加入一个mock的脚本

vue-cli-service serve --mode mock

  1. 在项目根目录新建一个.env.mock文件并赋值一个标志位VUE_APP_IS_MOCK=true
VUE_APP_IS_MOCK=true
VUE_APP_BASE_API = '/api'`
  1. 定义mock数据
export default {
  'get /role': (config) => {
    const rows = [{name: '角色1', id: 1}, {name: '角色2', id: 2}]
    const total = 2
    return Promise.resolve({
      rows,
      total,
      code: 200,
    });
  },
  'get /role/:id': (config, regexp) => {
    const url = config.url;
    const rs = regexp.exec(url);
    const id = rs[1];
    return Promise.resolve({
      code: 200,
      data: {
        id,
        name: '角色1'
      }
    })
  },
  'post /role': (config) => {
    const data = config.data;
    return Promise.resolve({
      code: 200,
      data: {
        ...data,
        id: 1
      },
      msg: '新增成功'
    })
  },
  'put /role': (config) => {
    const data = config.data;
    return Promise.resolve({
      code: 200,
      data: {
        ...data,
        id: 1
      },
      msg: '修改成功'
    })
  },
  'delete /role/:id': (config, regexp) => {
    const url = config.url;
    const rs = regexp.exec(url);
    const id = rs[1];
    return Promise.resolve({
      code: 200,
      msg: '删除成功'
    })
  },
};
  1. 将request.js包装一层

index.js

import baseRequest from './request';
import wrapperRequest from './wrapperRequest';

const isMock = !!process.env.VUE_APP_IS_MOCK;

// eslint-disable-next-line import/no-mutable-exports
let request = baseRequest;
if (isMock) {
  request = wrapperRequest;
}

export default request;

wrapperRequest.js

import { pathToRegexp } from 'path-to-regexp';
import mockData from '@/mock';
import request from './request';

let hasParseMock = false;
let regexps;
const cacheMap = {};

function wrapperRequest(config) {
  if (!hasParseMock) {
    hasParseMock = true;
    const keys = Reflect.ownKeys(mockData);
    regexps = keys.map((key) => {
      const keyStrs = key.split(' ');
      const method = keyStrs[0].toLocaleLowerCase();
      const path = keyStrs[1];
      const regexp = pathToRegexp(path);
      return {
        method,
        cb: mockData[key],
        regexp,
      };
    });
  }
  const requestMethod = (config.method || 'get').toLocaleLowerCase();
  const requestPath = config.url;
  let obj = cacheMap[`${requestMethod}-${requestPath}`];
  if (!obj) {
    obj = regexps.find((item) => item.method === requestMethod && item.regexp.test(requestPath));
    cacheMap[`${requestMethod}-${requestPath}`] = obj || true;
  }
  if (obj && obj !== true) {
    return obj.cb(config, obj.regexp);
  }
  return request(config);
}

export default wrapperRequest;

注意:需要安装path-to-regexp

  1. 运行命令,npm run mock启动项目