1.安装axios
npm install axios
2.安装mock
npm install mockjs
3.新建config.js
import axios from 'axios'
//创建一个axios实例
const service = axios.create({
//请求超时
timeout:60000
})
// 请求拦截器
service.interceptors.request.use(
config => {
return config
},
error => {
return Promise.reject(error)
}
)
// 响应拦截器
service.interceptors.response.use(
response => {
return response
},
error => {
return Promise.reject(error)
}
)
export default service
4.新建index.js , home.js
5.index.js
import Mock from 'mockjs'
import homeApi from './home'
//设置200-2000毫秒延时请求数据
Mock.setup({
timeout:'200-2000'
})
//拦截的是 /home/getData
Mock.mock(/\/home\/getData/,'get',homeApi.getData)
6.home.js
import Mock from 'mockjs'
let List = []
export default {
getData: () =>{
for (let i = 0; i < 7; i++) {
List.push(
Mock.mock({
vue: Mock.Random.float(100, 8000, 0, 2),
wechat: Mock.Random.float(100, 8000, 0, 2),
ES6: Mock.Random.float(100, 8000, 0, 2),
Redis: Mock.Random.float(100, 8000, 0, 2),
React: Mock.Random.float(100, 8000, 0, 2),
springboot: Mock.Random.float(100, 8000, 0, 2)
})
)
}
return {
code:2000,
data:{
List
}
}
}
}
7.在main.js中引入
import http from '@/api/config'
import './mock'
Vue.prototype.$http = http
8.在页面中使用
getData(){
this.$http.get('/home/getData').then(res => {
console.log(res.data)
})
}
10.