
正文
mockjs 在项目中vue项目中使用
提示:扫一扫查出行【扫一扫了解最新限行尾号】
复制提示
一、为什么要使用mockjs
总结起来就是在后端接口没有开发完成之前,前端可以用已有的接口文档,在真实的请求上拦截ajax,并根据mockjs的mock数据的规则,模拟真实接口返回的数据,并将随机的模拟数据返回参与相应的数据交互处理,这样真正实现了前后台的分离开发。
二、在vue的项目中怎么去使用mockjs
1、下载mockjs
npm install mockjs --save
2、使用mockjs
2.1在项目目录中新建mock/mockServer.js 模拟服务端
import Mock from 'mockjs'
const swipes = [
{
imgUrl:"https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1556531040198&di=c6dabc6bb5c6524f9b77ceded00d1fce&imgtype=0&src=http%3A%2F%2Fi3.hexun.com%2F2019-04-28%2F196992413.jpg"
},
{
imgUrl:"https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1556531040180&di=0feae9ec159834591880d72c34137235&imgtype=0&src=http%3A%2F%2Fm1080.com%2Fupimg%2Fzyzp1%2F145186.jpg"
},
{
imgUrl:"https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1556531040164&di=b228224bb92c8baa6fbfa1ac6d31398c&imgtype=0&src=http%3A%2F%2Fimg.smzy.com%2Fimges%2F2017%2F0510%2F20170510101016609.jpg"
}
];
const patients =[
{
id:'1',
title:'张大爷',
label:'男',
path:'/patient',
imgUrl:'../../static/images/20170622131955_h4eZS.thumb.700_0.jpeg'
},
{
id:'2',
title:'李大爷',
label:'男',
path:'/patient',
imgUrl:'../../static/images/20170622131955_h4eZS.thumb.700_0.jpeg'
},
{
id:'3',
title:'张奶奶',
label:'女',
path:'/patient',
imgUrl:'../../static/images/20170622131955_h4eZS.thumb.700_0.jpeg'
},
{
id:'4',
title:'李大爷',
label:'男',
path:'/patient',
imgUrl:'../../static/images/20170622131955_h4eZS.thumb.700_0.jpeg'
},
{
id:'5',
title:'王奶奶',
label:'女',
path:'/patient',
imgUrl:'../../static/images/20170622131955_h4eZS.thumb.700_0.jpeg'
}
];
Mock.mock('/swipes',swipes);
Mock.mock('/patients',patients);
Mock.mock("/patient", "post", (options)=>{
const jsonObj = eval('(' + options.body + ')');
const patient = patients.filter(p=>p.id == jsonObj.pid);
return patient[0];
});
2.2在main.js项目全局文件中引入mockServer
import './mock/mockServer' //加载mockServer
2.3前端发送ajax去请求mockServer 的 数据
/*
ajax请求函数模块
返回值: promise对象(异步返回的数据是: response.data)
*/
import axios from 'axios'
export default function ajax (url, data={}, type='GET') { return new Promise(function (resolve, reject) {
// 执行异步ajax请求
let promise
if (type === 'GET') {
// 准备url query参数数据
let dataStr = '' //数据拼接字符串
Object.keys(data).forEach(key => {
dataStr += key + '=' + data[key] + '&'
})
if (dataStr !== '') {
dataStr = dataStr.substring(0, dataStr.lastIndexOf('&'))
url = url + '?' + dataStr
}
// 发送get请求
promise = axios.get(url)
} else {
// 发送post请求
promise = axios.post(url, data)
}
promise.then(function (response) {
// 成功了调用resolve()
resolve(response.data)
}).catch(function (error) {
//失败了调用reject()
reject(error)
})
})
}
/*
包含n个接口请求函数的模块
函数的返回值: promise对象
*/
import ajax from './ajax'; //1、获取swipe的图片列表
export const reqSwipes = ()=>ajax(`/swipes`,); //2、获取所有病人信息列表
export const reqPatients = ()=>ajax(`/patients`); //3、根据pid获取病人信息
export const reqPatientByPid = (pid)=>ajax(`/patient`,{pid},"POST");







