微信小程序結(jié)合mock.js實現(xiàn)后臺模擬及調(diào)試
一、創(chuàng)建小程序項目

mock.js 從 https://github.com/nuysoft/Mock/blob/refactoring/dist/mock.js 下載
api.js:配置模擬數(shù)據(jù)和后臺接口數(shù)據(jù),通過DEBUG = true;//切換數(shù)據(jù)入口
let API_HOST = "http://xxx.com/xxx";
let DEBUG = true;//切換數(shù)據(jù)入口
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 {
// 模擬數(shù)據(jù)
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)',//庫存數(shù)量
'marketing_start': '@datetime()',
'marketing_stop': '@now()',
'price': '@integer(100,2000)',//現(xiàn)價,單位:分
'original_price': '@integer(100,3000)'
}]
})
// 輸出結(jié)果
// console.log(JSON.stringify(res, null, 2))
fn(res);
}
}
module.exports = {
ajax: ajax
}
index.js頁面
//index.js
//獲取應(yīng)用實例
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>
頁面顯示

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
table insertRow、deleteRow定義和用法總結(jié)
這篇文章主要對table insertRow、deleteRow定義和用法做下總結(jié),需要的朋友可以參考下2014-05-05
正則表達(dá)式判斷是否存在中文和全角字符和判斷包含中文字符串長度
對于一些更安全的容錯嚴(yán)重,需要用到2008-09-09
一文掌握J(rèn)avaScript數(shù)組常用工具函數(shù)總結(jié)
這篇文章主要介紹了一文掌握J(rèn)avaScript數(shù)組常用工具函數(shù)總結(jié),文章圍繞主題展開詳細(xì)的內(nèi)容介紹,具有一定的參考價值2022-06-06
ES6新特性三: Generator(生成器)函數(shù)詳解
這篇文章主要介紹了ES6新特性之Generator(生成器)函數(shù),簡單分析了Generator(生成器)函數(shù)的功能、定義、調(diào)用方法并結(jié)合實例形式給出了相關(guān)使用技巧,需要的朋友可以參考下2017-04-04

