一,安装:
npm install mockjs --save-dev
目录:
src 同级目录下新建 mock 文件夹 下 新建 mock.js 和 tags.js 文件
二,main.js 中导入:
require('@/mock/mock.js')
三,mock.js 文件:
const Mock = require('mockjs')// 设置拦截ajax请求的相应时间
Mock.setup({timeout: "10"
});// 自定义mockjs数据列表
let configArray = [];// 使用webpack的require.context()遍历所有mock文件
const files = require.context(".", true, /\.js$/);
files.keys().forEach(key => {if (key === "./mock.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);}
});
四,tags.js 文件
// 导入json数据
import PlanApproval from './PlanAndAllocation/PlanApproval/infoList.json'
import OwnersInfo from './PlanAndAllocation/DistributionByOwners/infoList.json'
export default {"post|/deletePlanApprovalInfoByIDList": (options) => {let jsonBody = JSON.parse(options.body)let info = jsonBody.infolet result = PlanApproval.filter(val => !info.includes(val.id))return {code: 200,message: "success",data: result};},"get|/getOwnersInfoByAll": () => {return {code: 200,message: "success",data: OwnersInfo};},"post|/EditOwnersInfo": (options) => {let jsonBody = JSON.parse(options.body)let info = jsonBody.infofor(let i=0; i<OwnersInfo.length; i++){if(OwnersInfo[i]['id'] == info.id){OwnersInfo[i] = info}}return {code: 200,message: "success",data: OwnersInfo};},"post|/AddOwnersInfo": (options) => {// 添加let jsonBody = JSON.parse(options.body)let info = jsonBody.infoOwnersInfo.push(info);return {code: 200,message: "success",data: OwnersInfo};},};
五,对接口
utils 文件夹 里面的 api.js 文件
AddOwnersInfo(info){return post('/AddOwnersInfo',{info: info})},
记得 在 main.js
// 设置$http全局变量
import serve from '@/utils/api'
Vue.prototype.$api = serve
五,调用接口
this.$api.AddOwnersInfo(this.InforFrom).then(res => {console.log(res)}).catch(err =>{console.log(err)})