vue uses mockJs to simulate data

Keywords: Javascript axios mockjs sftp Vue

In recent years, I have been developing in Java, and I have forgotten about the front-end technology (actually, I don't know how to do it). Recently, I participated in a project written in VUE + element UI + springboot. Because of the uncertain demand, I drew a demo interface first, and I didn't want to write the data. So I went online to check how to write mock. I spent an hour or two yesterday to figure out the routine Successful implementation. I haven't touched VUE ES5 ES6 before, so it's hard to write in some places. If you remember today, just record it.

Official document about mockjs https://github.com/nuysoft/Mock/wiki

1. Install mockjs and mocks

   npm install mock -S       npm install mockjs -S

2. Create the mock folder under the src file, and create mock.js, as follows:

import axios from 'axios';
import MockAdapter from 'axios-mock-adapter';
import { TimeLineData1, TimeLineData2, TimeLineData3, TimeLineData4} from './progressList';
import {getJobPrgsInfoByParameter} from '../api/api';

let _TimeLineData1 = TimeLineData1;
let _TimeLineData2 = TimeLineData2;
let _TimeLineData3 = TimeLineData3;
let _TimeLineData4 = TimeLineData4;

export default {
  /**
   * mock bootstrap
   */
  bootstrap() {
    let mock = new MockAdapter(axios);

    mock.onGet('/api/jobmonitor/getJobPrgsInfoByParameter').reply(config => {
        let req = config.params;
        let reqId = req.params.reqId;
        
        console.log(req.params);
        
        if(reqId == 'active'){
            return new Promise((resolve, reject) => {
                setTimeout(() => {
                  resolve([200, {
                      timeLineList: _TimeLineData1
                  }]);
                }, 1000);
              });
        }
        else if(reqId == 'wait'){
            return new Promise((resolve, reject) => {
                setTimeout(() => {
                  resolve([200, {
                      timeLineList: _TimeLineData2
                  }]);
                }, 1000);
              });
        }
        else if(reqId == 'finish'){
            return new Promise((resolve, reject) => {
                setTimeout(() => {
                  resolve([200, {
                      timeLineList: _TimeLineData3
                  }]);
                }, 1000);
              });
        }
        else{
            return new Promise((resolve, reject) => {
                setTimeout(() => {
                  resolve([200, {
                      timeLineList: _TimeLineData4
                  }]);
                }, 1000);
              });
        }
        
        
      });
    
  }
};

3. Create progressList.js and write mock data

const Mock = require("mockjs")
const Random = Mock.Random
const code = 200 

const TimeLineData1 = [];
const TimeLineData2 = [];
const TimeLineData3 = [];
const TimeLineData4 = [];

      for (let i = 0; i < Random.natural(5, 35); i++) {
        let timeLine = {
          timestamp: Random.date() + ' ' + Random.time(),
          _expanded: true,
          jobProgress :[]
        }
        for(let j=0; j< Random.natural(1, 9); j++){
              let progress = {
                      requestId: Random.guid(),
                      jobName: Random.name() + ' test',
                      currentStepId: 'step' + Random.natural(0,10),
                      currentStepStatus: Random.pick(['success', 'error']),
                      percentage: Random.natural(0,99),
                      category: Random.pick(['cv_locate', 'cv_availability']),
                      type: Random.pick(['sftp','http','ems','email','fix'])
              }
              timeLine.jobProgress.push(progress)
         }
        TimeLineData1.push(timeLine)
      }
      
      for (let i = 0; i < Random.natural(5, 35); i++) {
            let timeLine = {
              timestamp: Random.date() + ' ' + Random.time(),
              _expanded: true,
              jobProgress :[]
            }
            for(let j=0; j< Random.natural(1, 9); j++){
                  let progress = {
                          requestId: Random.guid(),
                          jobName: Random.name() + ' test',
                          percentage: 0,
                          category: Random.pick(['cv_locate', 'cv_availability']),
                          type: Random.pick(['sftp','http','ems','email','fix'])
                  }
                  timeLine.jobProgress.push(progress)
             }
            TimeLineData2.push(timeLine)
          }

      for (let i = 0; i < Random.natural(5, 30); i++) {
            let timeLine = {
              timestamp: Random.date() + ' ' + Random.time(),
              _expanded: true,
              jobProgress :[]
            }
            for(let j=0; j< Random.natural(1, 9); j++){
                  let progress = {
                          requestId: Random.guid(),
                          jobName: Random.name() + ' test',
                          percentage: 100,
                          currentStepStatus: Random.pick(['success', 'error']),
                          category: Random.pick(['cv_locate', 'cv_availability']),
                          type: Random.pick(['sftp','http','ems','email','fix'])
                  }
                  timeLine.jobProgress.push(progress)
             }
            TimeLineData3.push(timeLine)
          }
      
      for (let i = 0; i < Random.natural(5, 30); i++) {
            let timeLine = {
              timestamp: Random.date() + ' ' + Random.time(),
              _expanded: true,
              jobProgress :[]
            }
            for(let j=0; j< Random.natural(1, 9); j++){
                  let progress = {
                          requestId: Random.guid(),
                          jobName: Random.name() + ' test',
                          currentStepId: 'step' + Random.natural(0,10),
                          currentStepStatus: Random.pick(['success', 'error']),
                          percentage: Random.natural(0,99),
                          type: Random.pick(['sftp','http','ems','email','fix'])
                  }
                  timeLine.jobProgress.push(progress)
             }
            TimeLineData4.push(timeLine)
          }

Mock.setup({
    timeout: 0-3000
})

export { TimeLineData1,TimeLineData2,TimeLineData3,TimeLineData4 };

3. Unified management of API requests through api.js, through src/api

import axios from 'axios';

axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
axios.defaults.timeout = 60000
let base = '';

export const getJobPrgsInfoByParameter = params => { return axios.get('/api/jobmonitor/getJobPrgsInfoByParameter',{ params: params }).then(res => res.data); };

4. Page call

<script>
import Mock from '@/mock/mock.js';
import util from '../../common/js/util';
import moment from 'moment';
import {getJobPrgsInfoByParameter} from '../../api/api';

.....
export default {
    components: {
    },
        
    data() {
      return {
          listLoading : false,
            reqType :null,
            timeLineList:[]
      }
    },
   methods: {
       
    getJobPrgsInfoByParameter: function () {
        let para = {
            params:{
                reqId:this.reqType
            }
        };
        this.listLoading = true;
        Mock.bootstrap();
        this.timeLineList = [];
        getJobPrgsInfoByParameter(para).then(res=>{
            this.timeLineList = res.timeLineList;
        });
        this.listLoading = false;
        
    }
    
   },
   created(){
   },
   mounted() {
    eventBus.$on("progressListNode",this.busHandle);
   },
   beforeDestroy: function () {
       eventBus.$off('progressListNode', this.busHandle);
   },
   computed:{
   }
}

 

The data are as follows:

Posted by steveswt on Sun, 01 Dec 2019 17:23:28 -0800