1.可以创建 src > common > request.js
//引入mint-ui模块 使用“加载中”
import { Indicator } from "mint-ui";
//引入axios
import axios from "axios";
import store from '@/store/index.js';
import router from '@/router/index.js'
export default {
common: {
method: "GET",
data: {},
params: {},
headers: {},
},
$axios(options = {}) {
//如果有传method,就用传过来的method,否则用默认的method
options.method = options.method || this.common.method;
options.data = options.data || this.common.data;
options.params = options.params || this.common.params;
options.headers = options.headers || this.common.headers;
//请求前_显示加载中
Indicator.open("加载中...");
//是否为登录状态
if (options.headers.token) {//如果前端请求时候要求验证token
options.headers.token = store.state.user.token; //详情见vuex持久化存储博客
if (!options.headers.token) {//如果没有登录 跳转到登录页面
router.push('/login')
}
}
return axios(options).then((v) => {
let data = v.data.data
return new Promise((res, rej) => {
if (!v) return rej();
//如果有数据 关闭加载中 =》
setTimeout(() => {
Indicator.close();
}, 500)
res(data)
})
});
},
};
2.在含有购物车的组件中使用axios二次封装
<footer>
<div @click="addCart()" class="add-cart">加入购物车</div>
<div>立即购买</div>
</footer>
import http from "@/common/api/request.js";
methods: {
//请求商品数据 get请求
async getData() {
let id = this.$route.query.id;
let res = await http.$axios({
url: "/api/goods/id",
params: {
id,
},
});
this.goods = res; //对象
console.log(res);
},
//加入购物车 post请求
addCart() {
http
.$axios({
url: "/api/addCart",
method: "post",
data: {
goodsId: this.$route.query.id,
},
headers: {
token: true,
},
})
.then((res) => {
console.log(res);
});
},
},