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() }
标签:
vue
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通