方法一:
- 安装mockjs
npm install mockjs --save
- 在src文件夹先新建mock文件夹用于存放json数据
- 在vue.config.js文件中做配置
const mockdata = require('./src/mock/banner.json');
const mockdata1 = require('./src/mock/floor.json');
const mockuser= require('./src/mock/user.json');
module.exports={
devServer: {
port:8080,
before(app){
app.get('/goods/list',(req,res,next)=>{
res.json(mockdata);
}),
app.post('/user/list',(req,res,next)=>{
res.json(mockuser);
}),
app.post('/goods/list1',(req,res,next)=>{
res.json(mockdata1);
})
}
}
}
- 在组件中发起axios请求
mounted() {
// 发起请求
console.log("发起请求");
axios.get("/goods/list").then(res => {
this.data = res.data
console.log(this.data)
})
axios.post("/user/list").then(res => {
this.data = res.data
console.log(this.data)
})
axios.post("/rist/list").then(res => {
this.data = res.data
console.log(this.data)
})
},
5.控制台中得到结果
方法二:
- 安装mockjs
npm i mockjs --save
- 在根目录下新建.env.delopment文件
- 在src文件夹下新建mock文件夹
- 在mock文件夹下新建json文件
- 在index.js文件夹中实现接口封装
const Mock =require('mockjs')
const fs = require('fs')
const path = require('path')
// 用于被index.js进行调用
function getJsonFile (filePath) {
// 读取指定的json文件
const json = fs.readFileSync(path.resolve(__dirname, filePath), 'utf-8')
// 解析并返回
console.log(json)
return JSON.parse(json)
}
module.exports = function (app) {
if(process.env.MOCK = true){
app.get('/goods/list', (rep,res) => {
console.log('1234509876')
let json = getJsonFile('./floor.json')
res.json(Mock.mock(json))
})
app.post('/user/list', (rep,res)=> {
let json = getJsonFile('./user.json')
res.json(Mock.mock(json))
})
}
}
6.在vue.config.js文件中引入index.js
module.exports={
devServer: {
// 项目根目录下的 vue.config.js 的 devServe 中
before:require('./src/mock/index')
}
}
7.组件中发起axios请求
8.得到需要的数据