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


    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)
    })
    

    请求结果:
    效果图

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

  • 相关阅读:
    如何使用 systemctl 管理服务
    Linux 下 SVN 的安装和配置
    C语言程序设计
    mysql 常用关键字操作(字符串转数字,字符串截取)
    Spring入门学习---05
    Spring入门学习---03
    使用 TiUP 部署 TiDB 集群
    docker安装kafka+kafka-manager集群
    发发牢骚
    php修改JPG格式图片的dpi
  • 原文地址:https://www.cnblogs.com/yzyh/p/12683390.html
Copyright © 2020-2023  润新知