mock、json数据、mockAjax.js的准备
mock、json数据、mockAjax.js的准备
一、在项目中安装mockjs
npm install mockjs
二、json数据准备
src > mock > floor.json
[
{
"id": "001",
"name": "家用电器",
"keywords": [
"节能补贴",
"4K电视",
"空气净化器",
"IH电饭煲",
"滚筒洗衣机",
"电热水器"
],
"imgUrl": "/images/floor-1-1.png",
"navList": [
{
"url": "#",
"text": "热门"
},
{
"url": "#",
"text": "大家电"
},
{
"url": "#",
"text": "生活电器"
},
{
"url": "#",
"text": "厨房电器"
},
{
"url": "#",
"text": "应季电器"
},
{
"url": "#",
"text": "空气/净水"
},
{
"url": "#",
"text": "高端电器"
}
],
"carouselList": [
{
"id": "0011",
"imgUrl": "/images/floor-1-b01.png"
},
{
"id": "0012",
"imgUrl": "/images/floor-1-b02.png"
},
{
"id": "0013",
"imgUrl": "/images/floor-1-b03.png"
}
],
"recommendList": [
"/images/floor-1-2.png",
"/images/floor-1-3.png",
"/images/floor-1-5.png",
"/images/floor-1-6.png"
],
"bigImg": "/images/floor-1-4.png"
},
{
"id": "002",
"name": "手机通讯",
"keywords": [
"节能补贴2",
"4K电视2",
"空气净化器2",
"IH电饭煲2",
"滚筒洗衣机2",
"电热水器2"
],
"imgUrl": "/images/floor-1-1.png",
"navList": [
{
"url": "#",
"text": "热门2"
},
{
"url": "#",
"text": "大家电2"
},
{
"url": "#",
"text": "生活电器2"
},
{
"url": "#",
"text": "厨房电器2"
},
{
"url": "#",
"text": "应季电器2"
},
{
"url": "#",
"text": "空气/净水2"
},
{
"url": "#",
"text": "高端电器2"
}
],
"carouselList": [
{
"id": "0011",
"imgUrl": "/images/floor-1-b01.png"
},
{
"id": "0012",
"imgUrl": "/images/floor-1-b02.png"
},
{
"id": "0013",
"imgUrl": "/images/floor-1-b03.png"
}
],
"recommendList": [
"/images/floor-1-2.png",
"/images/floor-1-3.png",
"/images/floor-1-5.png",
"/images/floor-1-6.png"
],
"bigImg": "/images/floor-1-4.png"
}
]
三、对二中的json数据进行mock
src > mock > mockServe.js
import Mock from 'mockjs';
import floor from './floor.json';
//mock数据:第一个参数:请求地址,第二个参数:请求数据
Mock.mock("/mock/floor", { code: 200, data: floor });
四、mockAjax.js
src > api > mockAjax.js
import axios from "axios";
import nprogress from "nprogress";
import "nprogress/nprogress.css";
const requests = axios.create({
baseURL: "/mock",
timeout: 50000,
});
//请求拦截器,在发送请求之前做些什么
requests.interceptors.request.use((config) => {
nprogress.start();
return config;
})
//响应拦截器,对响应数据做点什么
requests.interceptors.response.use(res => {
nprogress.done();
return res.data;
}, (error) => {
alert("服务器响应数据失败");
})
export default requests;
五、mockAjax请求数据
project > src > api > index.js
import mockRequets from './mockAjax';
//获取floor数据
export const reqFloorList = () => mockRequets.get('/floor');