vue uses mock

download mock

npm install mock

Using mock.js in vue

1. Create a new mock module under src
Insert image description here

2. Create a new index.js file under the mock module to uniformly manage mock data
Insert image description here

import Mock from 'mockjs'

// 设置响应延时
Mock.setup({
	timeout: '200-600'//可以是整数,也可以是‘-’字符串
});

let configArray = [];

//使用webpack的require.context()遍历所有的mock文件
const files = require.context('.', true, /\.js$/);
files.keys().forEach((key) => {
	if(key === './index.js') return;
	configArray = configArray.concat(files(key).default);
});

//注册所有的mock服务
configArray.forEach((item) => {
	for(let [path, target] of Object.entries(item)){
		let protocol = path.split('|');
		Mock.mock(new RegExp('^' + protocol[1]), protocol[0],target);
	}
})

3. Place the required data sources in files in the same directory as index.js
Insert image description here

4.Introduce mock module into main.js
require('./mock')
Insert image description here

Guess you like

Origin blog.csdn.net/weixin_42215897/article/details/123548381