经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 移动开发 » 微信小程序 » 查看文章
微信小程序结合mock.js实现后台模拟及调试
来源:jb51  时间:2019/3/28 11:43:46  对本文有异议

一、创建小程序项目

mock.js 从 https://github.com/nuysoft/Mock/blob/refactoring/dist/mock.js 下载

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

  1. let API_HOST = "http://xxx.com/xxx";
  2. let DEBUG = true;//切换数据入口
  3. var Mock = require('mock.js')
  4. function ajax(data = '', fn, method = "get", header = {}) {
  5. if (!DEBUG) {
  6. wx.request({
  7. url: config.API_HOST + data,
  8. method: method ? method : 'get',
  9. data: {},
  10. header: header ? header : { "Content-Type": "application/json" },
  11. success: function (res) {
  12. fn(res);
  13. }
  14. });
  15. } else {
  16. // 模拟数据
  17. var res = Mock.mock({
  18. 'error_code': '',
  19. 'error_msg': '',
  20. 'data|10': [{
  21. 'id|+1': 1,
  22. 'img': "@image('200x100', '#4A7BF7','#fff','pic')",
  23. 'title': '@ctitle(3,8)',
  24. 'city': "@county(true)",
  25. 'stock_num': '@integer(0,100)',//库存数量
  26. 'marketing_start': '@datetime()',
  27. 'marketing_stop': '@now()',
  28. 'price': '@integer(100,2000)',//现价,单位:分
  29. 'original_price': '@integer(100,3000)'
  30. }]
  31. })
  32. // 输出结果
  33. // console.log(JSON.stringify(res, null, 2))
  34. fn(res);
  35. }
  36. }
  37. module.exports = {
  38. ajax: ajax
  39. }

index.js页面

  1. //index.js
  2. //获取应用实例
  3. var app = getApp()
  4. var API = require('../../utils/api.js')
  5. Page({
  6. data: {
  7. },
  8. onLoad: function () {
  9. console.log('onLoad')
  10. var that = this
  11. // 使用 Mock
  12. API.ajax('', function (res) {
  13. //这里既可以获取模拟的res
  14. console.log(res)
  15. that.setData({
  16. list:res.data
  17. })
  18. });
  19.  
  20. console.log(this.data.list)
  21. }
  22. })

index.wxml

  1. <!--index.wxml-->
  2. <block wx:for="{{list}}" wx:key="name">
  3. <view>{{item.title}}</view>
  4. <text>{{item.city}}</text>
  5. <view>
  6. <text>{{item.marketing_start}}</text>
  7. </view>
  8. <image src='{{item.img}}'></image>
  9. </block>

页面显示

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持w3xue。

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号