01、安装
安装mock
npm install mockjs
安装axios
npm install axios
02、新建一个config.js文件做axios拦截
import axios from ‘axios‘ // 创建一个实例 const service = axios.create({ //设置请求延迟时间 timeout: 3000 }) //请求的拦截 service.interceptors.request.use( config => { return config }, err => { console.log(err) } ) //响应的拦截 service.interceptors.response.use( response => { let res = {} res.status = response.status res.data = response.data return res }, err => console.log(err) ) // 输出 export default service
03、在入口文件main.js引入
import http from ‘./api/config‘ import ‘./mock‘ Vue.prototype.$http = http
04、建立mock文件夹,并新建index.js文件,用于设置mock和引用其他组件分出来的mock请求数据,便于数据分模块获取
index.js
home.js
import Mock from ‘mockjs‘ export default { getHomeData: () => { return { code: 20000, data: { videoData: [ { name: ‘SpringBoot‘,
//获取随机float value: Mock.Random.float(1000, 10000, 0, 3) }, { name: ‘iOS‘, value: Mock.Random.float(1000, 10000, 0, 3) }, { name: ‘php‘, value: Mock.Random.float(1000, 10000, 0, 3) }, { name: ‘h5‘, value: Mock.Random.float(1000, 10000, 0, 3) }, { name: ‘小程序‘, value: Mock.Random.float(1000, 10000, 0, 3) } ] } } } }
04、使用(在需要请求数据的界面使用)
this.$http.get(‘/home/gatData‘).then(res => { console.log(res) })