微信小程序——使用mock.js模拟数据

一,创建目录

再根目录utils目录下面创建 WxMock.js文件和api.js文件

二,WxMock.js 

WxMock.js下载地址:https://github.com/webx32/WxMock

Mock.js 使用方式见 http://mockjs.com/examples.html  

 

三,api.js

api.js:配置模拟数据和后台接口数据,通过 DEBUG = true;//切换数据入口



let API_HOST = "http://xxx.com/xxx";
let DEBUG = true;//切换数据入口
var Mock = require("./WxMock.js"); 
function ajax(data = '', fn, method = "get", header = {}) {
    if (!DEBUG) {
        wx.request({
            url: config.API_HOST + data,
            method: method ? method : 'get',
            data: {},
            header: header ? header : { "Content-Type": "application/json" },
            success: function (res) {
                fn(res);
            }
        });
    } else {
        // 模拟数据
        var res = Mock.mock({
            'error_code': '',
            'error_msg': '',
            'data|10': [{
                'id|+1': 1,
                'img': "@image('200x100', '#4A7BF7','#fff','pic')",
                'title': '@ctitle(3,8)',
                'city': "@county(true)",
                'stock_num': '@integer(0,100)',//库存数量  
                'marketing_start': '@datetime()',
                'marketing_stop': '@now()',
                'price': '@integer(100,2000)',//现价,单位:分  
                'original_price': '@integer(100,3000)'
            }]  
        })
        // 输出结果
       // console.log(JSON.stringify(res, null, 2))
        fn(res);
    }
}
module.exports = {
    ajax: ajax
}

 

四,页面调用

index.js

var API = require('../../utils/api.js')
Page({
    data: {
    },
    onLoad: function () {
        console.log('onLoad')
        var that = this
        // 使用 Mock
        API.ajax('', function (res) {
            //这里既可以获取模拟的res
            console.log(res)
            that.setData({
                list:res.data
            })
        });

        console.log(this.data.list)
    }
})

得到数据: 

 

参考文章:https://www.jianshu.com/p/1f4a4fa755bb

https://www.cnblogs.com/lguow/p/9138094.html 

  • 3
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值