mock.js的使用

161 阅读2分钟

1.搭建测试环境

1.1创建vue项目

vue create mock-demo 

1.2安装依赖

//使用axios发送  ajax
cnpm install axios --save
//使用mockjs产生随机数据
cnpm install mockjs --save-dev
//使用json5解决json文件,无法添加注释问题
cnpm install json5 --save-dev

2.mock的使用

  • 在mock-demo文件夹下创建一个mock文件夹
  • 在mock文件夹下创建一个testMock.js文件
  • 在testMock.js写入如下代码

2.1生成一个id

const Mock=require('mockjs')
let id=Mock.mock('@id')
console.log(id)

2.2生成一个对象

const Mock=require('mockjs')
let obj=Mock.mock({
    id: "@id()",//得到随机的id,对象
    username: "@cname()",//随机生成中文名字
    date: "@date()",//随机生成日期
    avatar: "@image('200x200','red','#fff','avatar')",//生成图片,参数:size, background, foreground, text
    description: "@paragraph()",//描述
    ip: "@ip()",//IP地址
    email: "@email()"//email
})
console.log(obj)

3.JSON5

3.1安装JSON5扩展

image.png

3.2引入JSON5库来解析JSON5格式

在mock文件夹下,新建testJSON5.js

const fs=require('fs')
const path=require('path')
const json5=require('json5')
//读取json文件
function getJsonFile(filePath){
    //path.resolve()该方法将一些的 路径/路径段 解析为绝对路径
    let json=fs.readFileSync(path.resolve(__dirname,filePath),'utf-8')
    //解析返回
    return json5.parse(json) //转换成js对象
}
var json=getJsonFile('./userInfo.json5')
console.log('json',json)

打印结果

image.png

4.mock与vue-cli结合

参考网址配置

cli.vuejs.org/zh/config/#…

webpack.js.org/configurati…

4.1新建vue.config.js

在根目录新建vue.config.js

module.exports = {
    devServer: {
        before: require('./mock/index.js')//引入mock/index.js
    }
}

4.2新建index.js

在mock文件下新建index.js

const fs = require('fs');
const path = require('path');
const Mock = require('mockjs');//mockjs 导入依赖模块
const JSON5 = require('json5');
//读取json文件
function getJsonFile(filePath) {
    //读取指定json文件
    var json = fs.readFileSync(path.resolve(__dirname,filePath), 'utf-8');
    //解析并返回
    return JSON5.parse(json);
}

//返回一个函数
module.exports = function(app){
    //监听http请求
    app.get('/user/userinfo', function (rep, res) {
        //每次响应请求时读取mock data的json文件
        //getJsonFile方法定义了如何读取json文件并解析成数据对象
        var json = getJsonFile('./userInfo.json5');
        //将json传入 Mock.mock 方法中,生成的数据返回给浏览器
        res.json(Mock.mock(json));
    });
}

4.3发送AJAX请求

在src\components\HelloWorld.vue中发送aja请求

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

4.4检验

image.png

4.5数据变化操作

若数据格式或数据改变,更改userInfo.json5文件即可

5.移除mock

当后台接口编写出来时,我们可以移除mock

配置网址cli.vuejs.org/zh/guide/mo…

5.1新建env.development

在项目根路径新建env.development

MOCK=true 

5.2完善mock\index.js

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');
            //将json传入 Mock.mock 方法中,生成的数据返回给浏览器
            res.json(Mock.mock(json));
        });
    }
}

6.原理图

image.png