简单使用mockjs,并且解决在mounted,created中调用出错问题
npm install mockjs -D
-
目录结构
-
src 下创建mock文件夹
-
创建两个js文件 index.js 、test.js
-
// index.js // 引入mockjs import Mock from 'mockjs' // 将数据导入进来 放到数组中 import test from "@/mock/test"; const mocks = [ ...test ] // 设置请求延时时间 Mock.setup({ // timeout: 2000 方式一 直接设置值 timeout: '200-600' // 方式二 设置区间 注意这个是一个字符串形式 }) // 是否进行拦截 在开发者模式下进行拦截 main.js中引入 export function DevFun() { function detectionFun(response) { // 判断是否是函数 if(response instanceof Function) { return response() }else { return Mock.mock(response) } } for (let i of mocks) { Mock.mock(new RegExp(i.url),i.type ||'get',detectionFun(i.response)) } }
-
test.js
-
const list = [ { id: 1, name: 'yu', phone: '1234', address: 'aaa', sex: 'name', }, { id: 2, name: 'yu', phone: '1234', address: 'aaa', sex: 'name', }, { id: 3, name: 'yu', phone: '1234', address: 'aaa', sex: 'name', }, ] export default [ { url: '/api/test', type: 'get', response: () => { return { code: 200, data: { total: list.length, items: list } } } } ]
-
-
main.js
-
// main.js中 只有在开发者模式下才调用 并且解决了 在页面中 created、mounted // 中调用 无法拦截问题 if (process.env.NODE_ENV === 'development') { const { DevFun } = require('./mock/index') DevFun() }
-
-
-
-
src下创建api文件夹
-
请求数据
-
queryMock.js
-
// 引入axios import axios from "axios"; // 使用 export function api(config) { const server = axios.create({ timeout:5000, baseURL: 'http://localhost:7777' }) return server(config) }
-
-
test.js
-
import {api} from "@/api/questMock"; export function getTestList() { return api({ method: 'get', url:'/api/test' }) }
-
-
-
-
页面中正常调用
-
mounted() { this.getTestList() }, methods: { getTestList() { getTestList().then(res => { console.log(res) }) } }
-
-