1.引入axios
npm install axios
2.src下面创建utils文件夹(下图)
service.js
import axios from "axios";
import { ElMessage } from "element-plus";
import { ElLoading } from "element-plus";
import store from "../store/index";
let loadingObj = null;
const Service = axios.create({
timeout: 8000,
baseURL: "https://xxx",
headers: {
"Content-type": "application/json;charset=utf-8",
"Authorization": store.state.uInfo.userInfo.token,
},
});
Service.interceptors.request.use((request) => {
loadingObj = ElLoading.service({
lock: true,
text: "Loading",
background: "rgba(0, 0, 0, 0.7)",
});
return request;
});
Service.interceptors.response.use(response => {
loadingObj.close();
return response.data;
}, error => {
loadingObj.close();
ElMessage({
message: error.meta.msg,
type: "error",
duration: 2000,
});
}
);
export const post = (config) => {
return Service({
...config,
method: "post",
data: config.data,
});
};
export const get = (config) => {
return Service({
...config,
method: "get",
params: config.data,
});
};
src/api/loginApi.js
import { post, get } from "@/utils/service";
const loginApi = {
login(data) {
return post({
url: "api/login",
data,
});
},
getList(data) {
return get({
url: "/list",
data,
});
},
};
export default loginApi;
页面引用
import loginApi from "@/api/loginApi";
setup中调用
const submitForm = () => {
loginApi.login(data.loginData).then(res => {
store.commit('setUserInfo', res.data);
localStorage.setItem('userInfo', JSON.stringify(res.data));
router.push({
path: '/user'
});
});
};
return {
...toRefs(data),
submitForm
};