vue-axios接口数据封装和使用方法:
在src文件夹下新建http文件夹
可以看见里面有三个子文件. env.js api.js request.js
env.js里面搭建环境:
export default {
dev: {
baseUrl: "https://localhost:8080"
},
test: {
baseUrl: "https://test.365msmk.com"
},
prod: {
baseUrl: "https://www.365msmk.com"
}
};
request.js里面创建axios实例,设置请求拦截和响应拦截
import axios from "axios";
const vipUrl = "/api/app/";
const prodUrl = "https://www.365msmk.com";
const service = axios.create({
baseURL: prodUrl + vipUrl
});
service.interceptors.request.use(
config => {
config.headers["deviceType"] = "H5";
return config;
},
);
service.interceptors.response.use(
response => {
return response;
},
);
export default service;
api.js里面封装各种业务的接口
import request from "./request";
export function getBanners() {
return request({
url: "/banner",
method: "GET"
});
}
export function getBattle() {
return request({
url: "/recommend/appIndex",
method: "GET"
});
}
export function get_sms_code(data) {
return request({
url: "/smsCode",
method: "POST",
data
});
}
export function userLogin(data) {
return request({
url: "login",
method: "POST",
data
});
}
export function lessonList(params) {
return request({
url: "courseBasis",
method: "GET",
params
});
}
用的时候直接在页面里面引入就可以了
<template>
<div class="swiper">
<van-swipe :autoplay="3000">
<van-swipe-item v-for="(image, index) in bannerList" :key="index">
<img v-lazy="image.banner_img" />
</van-swipe-item>
</van-swipe>
</div>
</template>
<script>
import { getBanners } from "../http/api";
export default {
name: "swiper",
data() {
return {
bannerList: []
};
},
created() {
this.getLunBo();
},
methods: {
getLunBo() {
getBanners().then(res => {
this.bannerList = res.data.data;
});
}
}
};
</script>
<style lang="scss" scoped>
.swiper {
.van-swipe {
width: 100%;
height: 400px;
.van-swipe-item {
img {
width: 100%;
height: 100%;
}
}
}
}
</style>
好了,以上就是axios的接口封装和使用