vue中axios+mock模拟数据测试

1.安装cli及所需包

npm i vue-cli -g
vue init
npm i mockjs -s
npm i axios -s

2.src文件夹下新建mock文件夹并新建index.js/extend.js/goods.js...

vue中axios+mock模拟数据测试_第1张图片

其中extends.js为自定义拓展功能,index.js为引入调用文件,goods.js为功能测试模块,还可以添加其他类型模块划分

3.main.js对mock以及axios引入

// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'
import axios from'axios'

// 使mock生效
import  './mock/'

Vue.prototype.$http = axios
Vue.config.productionTip = false

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  components: { App },
  template: ''
})

4.mock文件夹下文件

---index.js---

// 导入拓展模块
import './extends'
// 导入商品模块
import './goods'


---extends.js---

// 导入random拓展方法
import { Random } from 'mockjs'

// random 扩展一个功能
Random.extend({
  'fruit': function() {
    const arr = ['榴莲','香蕉','苹果','菠萝蜜','椰子']
    return this.pick(arr)
  }
})


---goods.js---

// 导入模拟假数据的包
import Mock from 'mockjs'

// 模拟假数据接口
Mock.mock("/api/getList",'get',{
  state: 200,
  message: "获取数据成功",
  'data|1-5': [
    {
      id: '@increment()',
      name: '@first()',
      age: '@natural(0,100)',
      hobby: '@paragraph(1,100)'
    }
  ]
})

Mock.mock('/api/postList','post',function (option) {
  console.log(option)
  return Mock.mock({
    state: 200,
    message: '@paragraph(1,100)'
  })
})

Mock.mock(/\/api\/sendId\/(\d+)/,'get',function(option) {
  const res = /\/api\/sendId\/(\d+)/.exec(option.url)[1]
  return Mock.mock({
    state: res,
    message: '发送成功',
    'data|1-3': [{
      id: res,
      name: '@fruit()',
      type: 'frult',
      describe: 'sdasd',
      img: '@dataImage(75x75)'
    }]
  })
})

5.Mock.vue下代码






6.运行图如下

vue中axios+mock模拟数据测试_第2张图片

7.代码请移步

https://github.com/Excusep/mockUse

你可能感兴趣的:(学前端)