首先要封装下axios,挂载到main.js文件中
//main中
//引入axios拦截器
import axios from "@/utils/request.js"
Vue.prototype.$axios = axios;
//request--axios封装
//1. 导入axios对象
import axios from "axios";
//2. 创建对象实例,create方法
const Server = axios.create({
baseURL: "http://39.100.7.70:81/",//请求接口的基础地址
timeout: 5000,//超时时间
})
// 3. 定义请求拦截器
Server.interceptors.request.use(function (config) {
return config;
}, function (error) {
return Promise.reject(error);
});
//4. 定义响应拦截器
Server.interceptors.response.use(function (response) {
//过滤出data的数据
return response;
}, function (error) {
return Promise.reject(error);
});
//5. 抛出对象即可
export default Server;
在src下新建api文件夹,里面是每个模块的api.js
//例如
import server from '@/utils/request.js'
export default {
//轮播图
getSwiper() {
return server.post('resources/carousel')
},
//各类商品数据 {"categoryName":"电视机"}
getShopList(data={}){
return server({
url:'/product/getPromoProduct',
method:'POST',
data:data
})
},
}
最后在组件中使用即可,先导入在使用
<template>
<div>
</div>
</template>
<script>
import particularsAPI from "../../api/particulars";
export default {
components: {},
name: "",
data() {
return {
},
created() {
this.gitListAll();
},
methods: {
async gitListAll() {
const { data: res } = await particularsAPI.gitListAll({
productID: this.id,
});
this.particularsList = res.Product[0];
},
},
};
</script>