vue-cli项目中使用mock结合axios-mock-adapter生成模拟数据

http://mockjs.com/  mockjs官网

https://www.npmjs.com/package/axios-mock-adapter   axios-mock-adapter官网

1.安装

  npm i mockjs axios-mock-adapter --save-dev

2.创建数据

创建文件夹

   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地址

var axios = require('axios')
var MockAdapter = require('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()

页面调用:

requestUsers().then((res) => {
    console.log(res)
})
requestGoods({id:1}).then((res) => {
    console.log(res)
})

  

效果:

 

posted @ 2018-03-08 16:32  老板、番茄炒蛋  阅读(8419)  评论(0编辑  收藏  举报