多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
### 一、axios-mock-adapter > axios-mock-adapter是一款axios的请求模拟调试器。在以vue做后台管理项目中,可以使用它来实现请求拦截并模拟后台回复 - **应用实例** ``` var axios = require('axios'); var MockAdapter = require('axios-mock-adapter'); // 设置模拟调试器实例 var mock = new MockAdapter(axios); // 模拟接收'/users'下的Get请求 // reply方法的参数格式(status,data,headers) mock.onGet('/users').reply(200, { users: [ { id: 1, name: 'John Smith' } ] }); //前端请求 axios.get('/users') .then(function(response) { console.log(response.data); }); ``` ### 二、安装&使用 #### 2.1 安装 ``` # 安装 npm install axios-mock-adapter --save-dev # 引入(ES6方式) import mockAdapter from 'axios-mock-adapter' import axios from 'axios' # 引入(CommonJS) var mockAdapter = require('axios-mock-adapter') var axios = require('axios') ``` #### 2.2 使用 ``` # 创建调试器实例 let mockAdapter = require('axios-mock-adapter') let axios = require('axios') let mock = new mockAdapter(axios); # 模拟接收到前端请求 mock.onGet('/users').reply(200,{ users:[ {id:1,name:'John Smith'} ] }) # 前端发送请求 axios.get('/users') .then(function(response){ console.log(response.data) }) ``` #### 返回一个回调函数 ``` mock.onGet('/users').reply(config=>{ // config是axios config,返回一个数组[status,data,headers] return [200,{ users:[{id:1,name:'Sophia'}] }] }) ``` #### 携带参数的响应 ``` mock.onGet('/users',{params:{searchText:'John'}}).reply(200,{ users:[ {id:1,name:'John Smith'} ] }) ``` #### 没有具体路径的时候 ``` // 拒绝所有的POST请求,返回HTTP 500 mock.onPost().reply(500); ``` ### 三、实例 ``` # loginUser.js import MockData from 'mock' let Random = MockData.Random const LoginUser = [ // 登录用户库 { id:1, userName :'admin', password:'123456', avatar:'https://xxxx.jpg', name: '王某某' } ] const users =[] // 用户列表 for(let i=0;i<66;i++){ users.push(MockData.mock({ id: Random.guid(), name: Random.cname(), addr: MockData.mock('@county(true)'), 'age|18-60': 1, birth: Random.date(), sex: Random.integer(0, 1) })) } export { LoginUser,users } # mock.js let axios =require('axios') let mockAdapter = require('axios-mock-adapter') let mock = new mockAdapter('axios') import { LoginUser,users} from './loginUser' let _Users = Users; # 登录 mock.onPost('/loginUser').reply(config=>{ // config.data即为前端传入的参数 let {username,password } = JSON.parse(config.data); return new Promise((resolve,reject)=>{ let user = null; setTimeout(()=>{ let hasUser = LoginUser.some(userItem=>{ if(userItem.userName == username&&userItem.password==password){ user = JSON.parse(JSON.stringify(u)); user.password = undefined; return true; } }); if(hasUser){ resolve([200,{code:200,msg:'请求成功',user}]) }else{ resolve([200,{code:500,msg:'账号或密码错误'}]) } },1000) }); }); # 获取用户列表 mock.onGet('/user/listpage').reply(config => { let {page, name} = config.params; let mockUsers = _Users.filter(user => { if (name && user.name.indexOf(name) == -1) return false; return true; }); let total = mockUsers.length; mockUsers = mockUsers.filter((u, index) => index < 20 * page && index >= 20 * (page - 1)); return new Promise((resolve, reject) => { setTimeout(() => { resolve([200, { total: total, users: mockUsers }]); }, 1000); }); }); # 删除用户 mock.onGet('/user/remove').reply(config => { let { id } = config.params; _Users = _Users.filter(u => u.id !== id); return new Promise((resolve, reject) => { setTimeout(() => { resolve([200, { code: 200, msg: '删除成功' }]); }, 500); }); }); # 批量删除用户 mock.onGet('/user/batchremove').reply(config => { let { ids } = config.params; ids = ids.split(','); _Users = _Users.filter(u => !ids.includes(u.id)); return new Promise((resolve, reject) => { setTimeout(() => { resolve([200, { code: 200, msg: '删除成功' }]); }, 500); }); }); # 编辑用户 mock.onGet('/user/edit').reply(config => { let { id, name, addr, age, birth, sex } = config.params; _Users.some(u => { if (u.id === id) { u.name = name; u.addr = addr; u.age = age; u.birth = birth; u.sex = sex; return true; } }); return new Promise((resolve, reject) => { setTimeout(() => { resolve([200, { code: 200, msg: '编辑成功' }]); }, 500); }); }); # 新增用户 mock.onGet('/user/add').reply(config => { let { name, addr, age, birth, sex } = config.params; _Users.push({ name: name, addr: addr, age: age, birth: birth, sex: sex }); return new Promise((resolve, reject) => { setTimeout(() => { resolve([200, { code: 200, msg: '新增成功' }]); }, 500); }); }); ```