欢迎光临,了解微信小程序开发,就上易用通!

使用mock.js提供模拟数据

发布:2018-01-25 09:03浏览: 来源:网络 作者:tianshu

使用mock.js提供模拟数据(图1)

 

github: https://github.com/nuysoft/Mock/tree/refactoring87

宗旨: 无需等待,让前端独立于后端进行开发

简介: Mock.js is a simulation data generator to help the front-end to develop and prototype separate from the back-end progress and reduce some monotony particularly while writing automated tests.

适合 
初学者: 如果你是一个刚刚开始写小程序的学习者,又苦于没有api拿来用,那么mock可以帮助你快速建立模拟数据,用于学习

开发者: 如果你的公司或者组织正在开发小程序,可是后台还没有能够提供给你调用接口,但是数据格式已经确定好,那么求人不如求己,自己先通过mock来模拟相关接口数据,先行一步。

开发使用 
1.引入mock.js 
在上面的github下下载mock.js 
https://github.com/nuysoft/Mock/blob/refactoring/dist/mock.js

 

  1. (function webpackUniversalModuleDefinition(root, factory) {
  2. if(typeof exports === 'object' && typeof module === 'object')
  3. module.exports = factory();
  4. else if(typeof define === 'function' && define.amd)
  5. define([], factory);
  6. else if(typeof exports === 'object')
  7. exports["Mock"] = factory();
  8. else
  9. root["Mock"] = factory();
  10. })(this, function() {
  11. return /******/ (function(modules) { // webpackBootstrap
  12. /******/ // The module cache
  13. /******/ var installedModules = {};
  14.  
  15. /******/ // The require function
  16. /******/ function __webpack_require__(moduleId) {
  17.  
  18. /******/ // Check if module is in cache
  19. /******/ if(installedModules[moduleId])
  20. /******/ return installedModules[moduleId].exports;

建立统一的网络接口  我们建立一个DEBUG来标志是否使用模拟数据

 

  1. let API_HOST = "https://xxx.com/xxx";
  2. let DEBUG = true;
  3.  
  4. var Mock = require('mocks.js')
  5. function ajax(data = '', fn, method = "get", header = {}) {
  6. if (!DEBUG) {
  7. wx.request({
  8. url: config.API_HOST + data,
  9. method: method ? method : 'get',
  10. data: {},
  11. header: header ? header : { "Content-Type": "application/json" },
  12. success: function (res) {
  13. fn(res);
  14. }
  15. });
  16. } else {
  17. // 模拟数据
  18. var res = Mock.mock({
  19. // 属性 list 的值是一个数组,其中含有 1 到 10 个元素
  20. 'list|1-10': [{
  21. // 属性 id 是一个自增数,起始值为 1,每次增 1
  22. 'id|+1': 1
  23. }]
  24. })
  25. // 输出结果
  26. console.log(JSON.stringify(res, null, 4))
  27. fn(res);
  28.  
  29. }
  30. }
  31.  
  32. module.exports = {
  33. ajax: ajax
  34. }

调用使用

 

  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. });
  15.  
  16. }
  17. })

发布模式  为了保证我们程序的最小化,发布模式下我们需要删除mock.js,并更改DEBUG为false,或者彻底删除api.js中的else部分

代办  由于mock.js中有对window等的封装,文件比较大,目前可能只能使用简单数据





免责声明:本站所有文章和图片均来自用户分享和网络收集,文章和图片版权归原作者及原出处所有,仅供学习与参考,请勿用于商业用途,如果损害了您的权利,请联系网站客服处理。