vue 使用mock (参照vue-element-admin)

文档结构

├── mock                       # 项目mock 模拟数据
│   │── index.js              # 模拟数据入口
│   │── utils.js                # 公用方法
│   └── test.js               # 测试模板 示例
├── src                        # 源代码
│   ├── api                    # 所有请求
│   │   ├── test.js            # 测试某个请求 示例
│   ├── utils                  # 全局公用方法
│   │   ├── request.js         # 封装请求
│   ├── views                  # views 所有页面
│   │   ├── test.vue           # 测试页面 示例
│   ├── main.js                # 入口文件 加载组件 初始化等 引用mock

准备工作

$ npm install mockjs

页面代码

mock/index.js

const Mock = require('mockjs')
const { param2Obj } = require('./utils')

const test= require('./test')

const mocks = [
  ...test
]

// for front mock
// please use it cautiously, it will redefine XMLHttpRequest,
// which will cause many of your third-party libraries to be invalidated(like progress event).
function mockXHR() {// mock patch
  // https://github.com/nuysoft/Mock/issues/300
  Mock.XHR.prototype.proxy_send = Mock.XHR.prototype.send
  Mock.XHR.prototype.send = function() {
    if (this.custom.xhr) {
      this.custom.xhr.withCredentials = this.withCredentials || false

      if (this.responseType) {
        this.custom.xhr.responseType = this.responseType
      }
    }
    this.proxy_send(...arguments)
  }

  function XHR2ExpressReqWrap(respond) {
    return function(options) {
      let result = null
      if (respond instanceof Function) {
        const { body, type, url } = options
        // https://expressjs.com/en/4x/api.html#req
        result = respond({
          method: type,
          body: JSON.parse(body),
          query: param2Obj(url),
        })
      } else {
        result = respond
      }
      return Mock.mock(result)
    }
  }

  for (const i of mocks) {
    Mock.mock(new RegExp(i.url), i.type || 'get', XHR2ExpressReqWrap(i.response))
  }
}

module.exports = {
  mocks,
  mockXHR,
}

mock/utils.js

/**
 * @param {string} url
 * @returns {Object}
 */
function param2Obj(url) {
  const search = decodeURIComponent(url.split('?')[1]).replace(/+/g, ' ')
  if (!search) {
    return {}
  }
  const obj = {}
  const searchArr = search.split('&')
  searchArr.forEach(v => {
    const index = v.indexOf('=')
    if (index !== -1) {
      const name = v.substring(0, index)
      const val = v.substring(index + 1, v.length)
      obj[name] = val
    }
  })
  return obj
}

/**
 * This is just a simple version of deep copy
 * Has a lot of edge cases bug
 * If you want to use a perfect deep copy, use lodash's _.cloneDeep
 * @param {Object} source
 * @returns {Object}
 */
function deepClone(source) {
  if (!source && typeof source !== 'object') {
    throw new Error('error arguments', 'deepClone')
  }
  const targetObj = source.constructor === Array ? [] : {}
  Object.keys(source).forEach(keys => {
    if (source[keys] && typeof source[keys] === 'object') {
      targetObj[keys] = deepClone(source[keys])
    } else {
      targetObj[keys] = source[keys]
    }
  })
  return targetObj
}

module.exports = {
  param2Obj,
  deepClone
}

mock/test.js

module.exports = [
  {
    url: '/test/getOrderList', // 注意:需要同目标api请求地址一样
    type: 'get',
    response: (config) => {
      return {
        success: true,
        code: 0,
        data: {orderList: [...]}
    }
  }
]

 src/api/test.js

import http from '@/utils/request.js'

// 收货地址 默认地址
export const getOrderList = (params) => {
  return http({
    url: '/test/getOrderList',
    method: 'GET',
    params: params,
  })
}

src/utils/request.js

import axios from 'axios'
import { Message } from 'view-design'

const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
})

service.interceptors.request.use(
  (config) => {
    
    }
    return config
  },
  (error) => {
    console.log(error)
    return Promise.reject(error)
  },
)

service.interceptors.response.use(
  (response) => {
    const res = response.data
    return res
  },
  (error) => {
    Message.error({
      content: error.message,
      type: 'error',
      duration: 5,
    })
    return Promise.reject(error)
  },
)

export default service

src/views/test.vue

<template>
  <div class="MyOrder"></div>
</template>


<script>
import { getOrderList } from '@/api/test.js'
export default {
  name: 'Order',
  data() {
    return {
        list: []
    }
  },
  created() {
    getOrderList().then((res) => {
        this.list= res.data.orderlist
    })
  }
}
</script>

main.js

// main.js
// 通过环境变量来判断是否需要加载启用
if (process.env.NODE_ENV === 'development') {
  const { mockXHR } = require('../mock')
  mockXHR()
}
原文地址:https://www.cnblogs.com/myflowers/p/15472430.html