zoukankan      html  css  js  c++  java
  • 【小程序】模拟数据支持(mockjs配置模拟服务器接口数据)

    utils目录

    ①下载mockjs(地址)放置utils目录中

    ②新建api.js :配置模拟数据以及后台接口,通过DEBUG=ture;  //切换数据接口

       配置如下:

    let API_HOST = "http://xxx.com/xxx";
    let DEBUG = true;//切换数据入口
    var Mock = require('mock.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
    }
    View Code

    ③在小程序访问数据的页面js中 定义变量注册,使用

       如下:

    //index.js
    //获取应用实例
    var app = getApp()
    var API = require('../../utils/api.js')
    Page({
        data: {
           goods:[]
        },
        onLoad: function () {
            var that = this// 使用 Mock配置的api接口
            API.ajax('', function (res) {
                that.setData({
                    goods:res.data
                })
            });
    
            console.log(this.data.goods)
        }
    })
    View Code

    那么,我们就可以在页面中使用数据了

    在api.js中,定义模拟数据的属性如图(可以再依mockjs文档的github地址定义其他我们所需要的数据格式):

    另外,也可将数据提取出,根据api中传入的请求类型datatype,返回对应的数据

    根据id返回res的改造版:

    mock文档手册:http://mockjs.com/0.1/

    参考资料:https://www.cnblogs.com/xzma/p/7591090.html

                  https://www.jianshu.com/p/9dbcfbe6130f

  • 相关阅读:
    edu_2_4_1
    edu_2_3_2
    edu_2_3_1
    edu_2_2_2
    edu_2_1_1
    edu_2_2_1
    hdu 1270 小希的数表
    hdu 2151 worm
    hdu1089 Ignatius's puzzle
    hdu 2190 悼念512汶川大地震遇难同胞——重建希望小学
  • 原文地址:https://www.cnblogs.com/smilexumu/p/9639147.html
Copyright © 2011-2022 走看看