Vue-mock封裝

1、模塊化封裝方式

  • 目錄結構如下

    –modules
    ----login.js
    ----user.js
    ----menu.js
    –index.js

  • login.js文件如下,可根據具體配置

// 獲取菜單信息
export function login () {
  return {
    url: '/login',
    type: 'post',
    data: 'token'
  }
}

export function userInfo () {
  return {
    url: '/api/user/info',
    type: 'get',
    data: user
  }
}
  • index.js 文件
import Mock from 'mockjs';
import * as login from './modules/login'
import * as user from './modules/user'
import * as menu from './modules/menu'

// true:開啓mock接口
// false:關閉mock接口
fnCreate(login, true)
fnCreate(user, true)
fnCreate(menu, true)

function fnCreate (mod, isOpen = true) {
  if (isOpen) {
    for (var key in mod) {
      ((res) => {
        if (res.isOpen !== false) {
          // let baseUrl="http://localhost:8080/";
          console.log(res.url)
          Mock.mock(new RegExp(res.url), res.type, (opts) => {
            opts['data'] = opts.body ? JSON.parse(opts.body) : null
            delete opts.body
            console.log('\n')
            console.log('%cmock攔截, 請求: ', 'color:blue', opts)
            console.log('%cmock攔截, 響應: ', 'color:blue', res.data)
            return res.data
          })
        }
      })(mod[key]() || {})
    }
  }
}

2、文件配置方式

  • 安裝json-server
npm install json-server
  • 在package.json添加啓動命令
  "mock": "babel-node build/mock-server.js --presets es2015,stage-0",
  • mock-server.js 文件配置
const jsonServer = require('json-server')
const path = require('path')
const server = jsonServer.create()
const middlewares = jsonServer.defaults()
const config = require("../src/mock/mock.js")

function parseKey(key) {
  var method = 'get';
  var path = key;

  if (key.indexOf(' ') > -1) {
    var splited = key.split(' ');
    method = splited[0].toLowerCase();
    path = splited[1];
  }
  return { method: method, path: path };
}

// Set default middlewares (logger, static, cors and no-cache)
server.use(middlewares)

function createMockHandler(method, path, value) {
  return function mockHandler(...args) {
    const res = args[1];
    if (typeof value === 'function') {
      value(...args);
    } else {
      res.json(value);
    }
  };
}

Object.keys(config).forEach(function (key) {
  var keyParsed = parseKey(key);
  if(!server[keyParsed.method]){
    console.error('method of ' + key + ' is not valid')
  }
  if(!(typeof config[key] === 'function' || typeof(config[key]) === 'object')){
    console.error('mock value of ' + key + ' should be function or object or string, but got ' + typeof(config[key]))
  }
  server[keyParsed.method](keyParsed.path, createMockHandler(keyParsed.method, keyParsed.path, config[key]));
});


server.use(jsonServer.bodyParser)

// mock地址:localhost:3000
server.listen(3000, () => {
  console.log('Mock Server is running')
})
  • mock.js 文件
// 啓動mock: npm run mock
const mock = {}
require('fs').readdirSync(require('path').join(`${__dirname}`)).filter(p=>`${p}`!=='mock.js').forEach((file) => {
  Object.assign(mock, require(`./${file}`))
})

module.exports = mock
  • mock數據文件(mock.js 在相同目錄)
const Mock = require('mockjs')

module.exports = {
 'GET /sys/user': function (req, res) {
    let res_json = {
      code: 200,
      msg: 'success',
      data: userList
    };
    res.status(200).json(res_json).end()
  }
 }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章