微信小程序 + mock.js 實現后台模擬及調試


一、創建小程序項目

mock.js 從 https://github.com/nuysoft/Mock/blob/refactoring/dist/mock.js 下載

api.js:配置模擬數據和后台接口數據,通過 DEBUG = true;//切換數據入口

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
}

index.js頁面

//index.js
//獲取應用實例
var app = getApp()
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)
    }
})

index.wxml

<!--index.wxml-->
<block wx:for="{{list}}" wx:key="name">
  <view>{{item.title}}</view>
  <text>{{item.city}}</text>
  <view>
    <text>{{item.marketing_start}}</text>
  </view>
  <image src='{{item.img}}'></image>
</block>

頁面顯示

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM