新建拦截规则
路径/src/mock/index.js
import Mock from 'mockjs' const Random = Mock.Random var listData = function() { let _data = [] for (let i = 0; i < 20; i++) { let newList = { // 详细 规则 参照mockjs官网 title: Random.csentence(5, 30), // Random.csentence( min, max ) imgSrc: Random.dataImage('200x160', '这是图片中的文本'), // Random.dataImage( size, text ) 生成图片(base64位数据格式) author_name: Random.cname(), // Random.cname() 随机生成中文名 date: Random.date() + ' ' + Random.time() // Random.date()指示生成的日期字符串的格式,默认为yyyy-MM-dd;Random.time() 返回一个随机的时间字符串 } _data.push(newList) } return {_data: _data} } // url为要拦截的请求地址 请求方式 请求数据(规则) (此处api会被mockjs拦截) Mock.mock('/getNewList', 'get', listData)在main.js中引用
import Vue from 'vue'; import App from './App.vue'; import router from './router'; import store from './model'; // 引用mock import './mock'; Vue.config.productionTip = false; new Vue({ router, store, render: (h) => h(App) }).$mount('#app');注册所有mock服务
路径/src/mock/index.js
// 首先引入Mock import Mock from 'mockjs'; // 设置拦截ajax请求的相应时间 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) => { // eslint-disable-next-line no-restricted-syntax for (const [path, target] of Object.entries(item)) { const protocol = path.split('|'); Mock.mock(new RegExp(`^${protocol[1]}`), protocol[0], target); } });在mock文件夹下新建mock规则
路径/src/mock/news.js
const mewsList = [{title: 'haah', content: '21312'}]; const mewsList = [{title: 'haah', content: '21312'}]; export default { 'get|/getUserList': (option) => ({ statusCode: 0, message: 'success', data: demoList }), 'get|/getChartList': (option) => ({ statusCode: 0, message: 'success', data: demoList }), };在main.js中引用
import Vue from 'vue'; import App from './App.vue'; import router from './router'; import store from './model'; // 引用mock import './mock'; Vue.config.productionTip = false; new Vue({ router, store, render: (h) => h(App) }).$mount('#app');