赞
踩
1,封装axios实例 request.js
- const axios = require('axios');
-
- // 创建一个axios实例
- const service = axios.create({
- baseURL: "https://ip:port",
- timeout: 60000
- });
-
- export default service
2,封装请求 api.js
- import service from 'request'
- import axios from "axios";
-
- export const canCancelApi = (data, cancel) => {
- return service({
- url: '/api/test',
- method: 'post',
- data,
- cancelToken: new axios.CancelToken((c) => {
- cancel && cancel(c)
- })
- })
- }
3,调用api
- import {onBeforeUnmount} from 'vue'
- import {canCancelApi} from "api";
-
-
- const apiCancel = null
- // 通过回调接收caccel方法
- canCancelApi(params, (cancle) => {
- apiCancel = cancle
- }).then(res => {})
-
- onBeforeUnmount(() => {
- if(apiCancel){
- // 关闭页面时如果请求存在则取消请求
- apiCancel('custom-cancel')
- }
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。