在vue中使用Mock

1. 安装插件

npm i -D mockjs
npm i -D json5


2. 在根目录下新建Mock文件夹,并新建index.js、test.json5

mkdir Mock
touch index.js test.json5
// index.js
const Mock = require('mockjs')
const path = require('path')
const fs = require('fs')
const json5 = require('json5')

const getJsonFile = (filepath)=>{
  const data = fs.readFileSync(path.resolve(__dirname,filepath),'utf-8')
  return json5.parse(data)
}

const json = getJsonFile('./test.json5')
// express
const API = (app) => {
  if(process.env.MOCK === 'true') {

    //  req 表示的请求 res表示的响应
    app.get('/mock/test', (req, res) => {
      const data = Mock.mock(json)
      // res.send res.json
      res.json(data)
    })
  }
}

module.exports = API
// test.json5
{
  'list|1-10': [{
    'id|+1': 1,
    'createTime': "@datetime('yyyy-MM-dd HH:mm:ss')",
    'chinese': '@cword(3)',
    'english': '@word()',
    'phonetic': '@word()',
    'example': '@sentence()',
  }]
}

3. 修改vue.config.js

module.exports = {
  devServer:{
    // 拦截器
    before:require('./mock')
  }
}

4. api文件新增函数

// 测试Mock
export function testMock() {
  return axios({
    method: 'get',
    url: '/mock/test',
  })
}

5. 组件内使用

testMock().then((res) => {
        console.log(res)
        const {list} = res?.data;
        this.list = [...list];
        this.total = this.list.length;
      })

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值