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...

其中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: '<App/>'
})

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下代码

<template>
 <div class="hello">
   <p>学习mock</p>
   <hr>
   <button @click="getData()">get获取数据</button>
   <button @click="postData()">post传数据</button>
   <button @click="sendDataId()">传id</button>
 </div>
</template>

<script>
export default {
  name: 'HelloWorld',
  data () {
    return {
      msg: 'Welcome to Your Vue.js App',
    }
  },
  methods:{
    async getData() {
      const { data : res} = await this.$http.get('/api/getList')
      console.log({res})
    },
    async postData() {
      const { data : res} = await this.$http.post('/api/postList',{name:'sds',age:18,hobby:'sdsd'})
      console.log({res})
    },
    async sendDataId(id) {
      id = Math.random()*100+1
      const { data : res} = await this.$http.get(`/api/sendId/${id}`)
      console.log(res)
    }
  }
}
</script>

<style scoped>
  .hello {
    padding: 20px;
  }
  hr {
    margin: 20px 0;
  }
  button {
    margin-left: 10px;
    padding: 4px 10px;
    background: yellowgreen;
    color: #fff;
    outline: none;
    border: none;
    border-radius: 3px;
  }
</style>

6.运行图如下

7.代码请移步

https://github.com/Excusep/mockUse

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐