Mock学习

发布时间 2023-04-01 16:05:20作者: 天叔

mock原理图

 

mock环境配置

1:vue create mock-demo(本地用vue3)

2:npm install axios --save

3:npm install mockjs --save-dev

4:npm install json5 --save-dev

5:进VS Code中下载json5 syntax插件

 

代码配置部署

1:进入mock-demo目录

2:文件结构与测试代码如下

 

 3:各文件如下

//useInfo.json5
{
  id: "@id()",
  username: "@cname()",
  date: "@date()",
  avatar: "@image('200x200', 'red', '#fff', 'avatar')",
  description: "@paragraph()",
  ip: "@ip()",
  email: "@email()",
}


// index.js
const fs = require('fs')
const path = require('path')
const JSON5 = require('json5')
const Mock = require("mockjs")

function getJsonFile(filePath) {
  var json = fs.readFileSync(path.resolve(__dirname, filePath), 'utf-8')
  // console.log(json)
  return JSON5.parse(json) 
}

module.exports = function(app) {

  if (process.env.Mock == 'true') {
    app.get('/user/userInfo', function(rep, res) {
      var json = getJsonFile('./userInfo.json5')
 
      res.json(Mock.mock(json))
    })
  }
}
// vue.config.js
module.exports = {
  devServer: {
    before: require('./mock/index.js')
  }
}


// HelloWorld.vue
<template>
  <div class="hello">
   
  </div>
</template>

<script>
import axios from 'axios'

export default {
  name: 'HelloWorld',
  mounted(){
    axios.get('/user/userInfo').then((res) => {
      console.log(res)
    }).catch((err) => {
      console.log(err)
    })
  }
}
</script>

<style scoped>
</style>

 

4:在项目根目录执行npm run serve,进入对应网页观看结果

 

mock移除

在index.js中设置if判断后,在根目录下建立.env.development文件,可通过true或false进行mock是否移除

 

其它还可进行增删改、分页Mock,但个人是全栈,所以不继续关注了