1.安装
npm i mockjs axios --save-dev
npm i mockjs axios-mock-adapter --save-dev
2.创建数据
// 文件夹配置
----mock
--------data
------------good.js
------------user.js
--------index.js
users.js:
import Mock from "mockjs"
const Users = [];
for (let i=0; i<100; i++){
Users.push(Mock.mock({
id: Mock.Random.integer(60, 100),
time: Mock.Random.datetime(),
desc: Mock.Random.cparagraph()
}))
}
export {Users}
goods.js:
import Mock from "mockjs"
const Goods = []
for (let i=0; i<10; i++){
Goods.push(Mock.mock({
id: Mock.Random.integer(60, 100),
desc: Mock.Random.cparagraph(10,20),
img: Mock.Random.image('200x100', '#4A7BF7',i)
}))
}
export {Goods}
index.js-通过axios-mock-adapter生成代理api地址
import axios from 'axios'
import MockAdapter from 'axios-mock-adapter'
import { Goods } from './data/goods'
import { Users } from './data/users'
export default {
init() {
var mock = new MockAdapter(axios)
mock.onGet('/users').reply(200, {
code: 1001,
msg: '请求成功',
Users
})
// mock.onGet('/goods').reply(200, {
// code: 1001, msg: '请求成功', Goods
// })
mock.onGet('/goods').reply(config => {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve([
200,
{
goods: Goods,
config: config.params
}
])
}, 500)
})
})
}
}
通过api.js对api请求统一的管理
import axios from 'axios'
// 真实数据增加此项配置
let base = ''
export const requestUsers = params => axios.get(`${base}/users`).then(res => res.data)
export const requestGoods = params => {
return axios.get(`${base}/goods`, { params: params }).then(res => res.data)
}
最后在main.js里面进行初始化
import Mock from './mock'
Mock.init()
页面调用:
import { requestUsers, requestGoods } from '../api'
requestUsers().then((res) => {
console.log(res)
})
requestGoods({id:1}).then((res) => {
console.log(res)
})
请求结果: