mockjs+vue-cli结合json5使用

安装
(1)npm install axios --save
(2)npm install mockjs --save-dev
(3)npm install json5 --save-dev (记得编辑器安装json5插件)

// 1.vue.config.js
devServer: {
    before: require('./src/mock/index.js'),
    open: true,
    host: 'xxxxxxxxx', ip地址
    port: 8080,
    hotOnly: true,
    watchContentBase: true,
    proxy: {
      "/api": {
        target: "http://xxxxxxxx:8080",
        pathRewrite: {
          "^/api": ""
        }
      }
    }
  }
// 2.mock文件夹
index.js
const fs = require('fs');
const path = require('path');
const Mock = require('mockjs');
const JSON5 = require('json5');

// 读取json文件
function getJsonFile(filePath) {
  let json = fs.readFileSync(path.resolve(__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) {
      // getJsonFile方法定义了读取json文件
      let json = getJsonFile('./userInfo.json5');
      // 将json传入Mock.mock方法中,生成的数据返回浏览器
      res.json(Mock.mock(json));
    })
    app.get('/user/goods', function (rep, res) {
      // getJsonFile方法定义了读取json文件
      let json = getJsonFile('./goods.json5');
      // 将json传入Mock.mock方法中,生成的数据返回浏览器
      res.json(Mock.mock(json));
    })
  }
}
userInfo.json5
{
    id: "@id()", 
    username: "@cname()", // 随机生成中文名
    date: "@date()", // 随机生成日期
    avatar: "@image('200x200','red','#fff','avatar')", // 随机生成图片
    description: "@paragraph()", // 随机生成描述
    ip: "@ip()", // 随机IP
    email: "@email()", // 邮件
    "array|1-4": [
        {
            "id|+1": 1, 
            name: "@cname"
        }
    ]
}

// 3.最外层目录
.env.development
MOCK = true

// 4.组件中使用
getData() {
      this.axios.get('/api/user/userinfo').then((result) => {
        console.log(res);
      }).catch((err) => {
        console.log(err);
      });
    }
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容