others linux服务器运维 django3 监控 k8s golang 数据库 大数据 前端 devops 理论基础 java oracle 运维日志

mock.js 快速入门

访问量:1344 创建时间:2020-09-16

官网:http://mockjs.com/

mock使用

C:\Users\Administrator>cd Desktop

C:\Users\Administrator\Desktop>vue create mock-learn
Vue CLI v4.5.4
┌─────────────────────────────────────────┐
│                                         │
│   New version available 4.5.4 → 4.5.6   │
│    Run npm i -g @vue/cli to update!     │
│                                         │
└─────────────────────────────────────────┘
? Please pick a preset: Manually select features
? Check the features needed for your project: Choose Vue version, Babel, Linter
? Choose a version of Vue.js that you want to start the project with 2.x
? Pick a linter / formatter config: Standard
? Pick additional lint features: Lint on save
? Where do you prefer placing config for Babel, ESLint, etc.? In dedicated config files
? Save this as a preset for future projects? No

Vue CLI v4.5.4
✨  Creating project in C:\Users\Administrator\Desktop\mock-learn.
�  Initializing git repository...
⚙️  Installing CLI plugins. This might take a while...

> yorkie@2.0.0 install C:\Users\Administrator\Desktop\mock-learn\node_modules\yorkie
> node bin/install.js

setting up Git hooks
done

> core-js@3.6.5 postinstall C:\Users\Administrator\Desktop\mock-learn\node_modules\core-js
> node -e "try{require('./postinstall')}catch(e){}"

> ejs@2.7.4 postinstall C:\Users\Administrator\Desktop\mock-learn\node_modules\ejs
> node ./postinstall.js

added 1250 packages from 918 contributors in 58.628s

53 packages are looking for funding
  run `npm fund` for details

�  Invoking generators...
�  Installing additional dependencies...

added 111 packages from 57 contributors in 16.498s

63 packages are looking for funding
  run `npm fund` for details

⚓  Running completion hooks...

�  Generating README.md...

�  Successfully created project mock-learn.
�  Get started with the following commands:

 $ cd mock-learn
 $ npm run serve
C:\Users\Administrator\Desktop\mock-learn>npm install axios --save
C:\Users\Administrator\Desktop\mock-learn>npm install mockjs json5 --save-dev
const Mock = require('mockjs')

let id = Mock.mock('@id')
let obj = Mock.mock(
  {
    id: '@id()', //随机id
    username: '@cname()', //随机中文名
    data: "@date()", //随机日期
    avatar: "@image('200x200','red','#fff','avatar')", //生成图片url
    description: "@paragraph()",
    ip: "@ip()",
    email: "@email()"
  }
)

console.log(id)
console.log(obj)

#创建userinfo.json5文件
  {
    id: '@id()', //随机id
    username: '@cname()', //随机中文名
    data: "@date()", //随机日期
    avatar: "@image('200x200','red','#fff','avatar')", //生成图片url
    description: "@paragraph()",
    ip: "@ip()",
    email: "@email()"
  }
#创建testJSON5.js
const fs = require('fs')
const path = require('path')
const JSON5 = require('json5')

var json = fs.readFileSync(path.join(__dirname, './userinfo.json5'), 'utf-8')

var obj = JSON5.parse(json)

console.log(obj)
#在console中执行node testJSON5.js
C:\Users\Administrator\Desktop\mock-learn\mock>node testJSON5.js
{
  id: '@id()',
  username: '@cname()',
  data: '@date()',
  avatar: "@image('200x200','red','#fff','avatar')",
  description: '@paragraph()',
  ip: '@ip()',
  email: '@email()'
}
#在项目根目录创建配置文件vue.config.js,内容如下:
module.exports = {
  devServer: {
    before: require('./mock/index.js')
  }
}
#在mock目录创建index.js文件,内容如下:
const fs = require('fs')
const path = require('path')
const Mock = require('mockjs')
const JSON5 = require('json5');
// 读取json文件
function getJsonFile(filePath) {
  var json = fs.readFileSync(path.join(__dirname, filePath), 'utf-8');
  return JSON5.parse(json);
}
//返回一个函数
module.exports = function (app) {
  app.get('/user/userinfo', function (rep, res) {
    //每次响应请求读取mock data的json文件,getJsonFile 定义如何读取文件解析成json对象
    var json = getJsonFile('./userinfo.json5');
    //返回随机数给浏览器
    res.json(Mock.mock(json));
  })
}
#修改src/components/HelloWorld.vue
<script>
import axios from 'axios'

export default {
  name: 'HelloWorld',
  props: {
    msg: String
  },
  mounted (){
    axios.get('/user/userinfo')
    .then(res => {
      console.log(res)
    })
    .catch( err => {
      console.error(err)
  })
  }

}
</script>
#保存后运行npm run serve,访问浏览器http://localhost:8080/,通过F12查看

mock移除

在根目录创建项目环境变量文件.env.development. 等后端接口开发完成后将变量设为false

MOCK = true

修改mock/index.js,增加一个判断条件process.env.MOCK,在MOCK为true时使用mock,否则不适用mock

const fs = require('fs')
const path = require('path')
const Mock = require('mockjs')
const JSON5 = require('json5');


// 读取json文件
function getJsonFile(filePath) {
  var json = fs.readFileSync(path.join(__dirname, filePath), 'utf-8');
  return JSON5.parse(json);
}

//返回一个函数
module.exports = function (app) {
  if (process.env.MOCK == 'true') {
    //监听http请求
    app.get('/user/userinfo', function (rep, res) {
      //每次响应请求读取mock data的json文件,getJsonFile 定义如何读取文件解析成json对象
      var json = getJsonFile('./userinfo.json5');
      //返回随机数给浏览器
      res.json(Mock.mock(json));
    })
  }
}
登陆评论: 使用GITHUB登陆