一,安装
npm install mockjs --save-dev
npm install json5 --save-dev
npm install axios --save
二,每个文件内容
目录:
流程:
Home.vue执行getUserInforList()
调用main.js中全局变量$api
调用/utils/api下的getUserInfor()
通过request.js包装好的get方法请求接口‘/user/getUserInfor’
通过devServer配置,拦截http请求
mock模拟后端服务监听http请求,写接口对数据进行操作
(1)vue.config.js
module.exports = {devServer: {before: require('./src/mock/index.js')}
}
(2)mock/index.js
const fs = require('fs')
const path = require('path')
const Mock = require('mockjs')
const JSON5 = require('json5')// 读取json文件
function getJSONFile(filePath){var json = fs.readFileSync(path.resolve(__dirname, filePath), 'utf-8')return JSON5.parse(json)
}module.exports = function(app){// 监听http请求app.get('/user/getUserInfor', function(rep, res){var json = getJSONFile('./user/userInfor.json5')res.json(Mock.mock(json))})
}
(3)main.js
// 设置$http全局变量
import serve from '@/utils/api'
Vue.prototype.$api = serve
(4)utils/request.js
// 引用axios
import axios from 'axios';
// import qs from 'qs'const instance = axios.create({baseURL: 'http://localhost:8080',withCredentials: true,timeout: 5000,headers:{ "Access-Control-Allow-Origin": '*',"Access-Control-Allow-Headers": 'Origin, Content-Type, X-Auth-Token',"Access-Control-Allow-Methods": "POST, GET, PUT, OPTIONS, DELETE" ,},});//http request 拦截器
instance.interceptors.request.use(config => {return config},err => {return Promise.reject(err)}
)//http response 拦截器
instance.interceptors.response.use(response => { return response },err => {return Promise.reject(err)}
) export function get(url, params){ return new Promise((resolve, reject) =>{ instance.get(url, { params: params }) .then(res => { resolve(res.data); }) .catch(err => { console.log(err)reject(err.data) }) });}export function post(url, params) { return new Promise((resolve, reject) => { instance.post(url, params) // instance.post(url, qs.stringify(params)) .then(res => { resolve(res.data); }) .catch(err => { console.log(err) reject(err.data) }) });}export function deletefn(url) { return new Promise((resolve, reject) => { instance.delete(url) .then(res => { resolve(res.data); }) .catch(err => { reject(err.data) }) });}export function deletefn1(url, params) { return new Promise((resolve, reject) => { instance.delete(url, { params: params }) .then(res => { resolve(res.data); }) .catch(err => { reject(err.data) }) });}export function put(url, params) { return new Promise((resolve, reject) => { instance.put(url, params) .then(res => { resolve(res.data); }) .catch(err => { reject(err.data) }) });}
(5)utils/api.js
import { get } from '@/utils/request'const serve = {getUserInfor(){return get('/user/getUserInfor',{})},}
export default serve
(6)home.vue
<script>
export default {name: 'Home',data(){return{}},mounted() {this.getUserInforList()},methods:{getUserInforList(){this.$api.getUserInfor().then(res => {console.log('请求结果:', res)}).catch(err => {console.log(err)})}}
}
</script>