官网: https://www.axios-http.cn/docs/interceptors
- steps1:
安装 npm install axios -s - steps2:
/src/api/request.js 文件 >>> 拦截器
import axios from 'axios'
// 如果没用element-plus就不引入
import { ElMessage } from 'element-plus'const service = axios.create()
const NETWORK_ERROR = '网络错误...'
// 添加请求拦截器
service.interceptors.request.use(function (config) {// 在发送请求之前做些什么return config},function (error) {// 对请求错误做些什么return Promise.reject(error)}
)// 添加响应拦截器
service.interceptors.response.use((res) => {const { code, data, msg } = res.dataif (code === 200) {return data} else {ElMessage.error(msg || NETWORK_ERROR)return Promise.reject(msg || NETWORK_ERROR)}
})function request(options) {options.method = options.method || 'get'return service(options)
}
export default request
- steps3:
/src/api/api.js 文件 >>> 接口
/*** 整个项目api的统一管理*/
import request from './request'export default {/*** 首页左侧表格数据* @returns tableList*/getTableData() {return request({url: '/api/home/getTableData',method: 'get'})}
}
-
steps4:
main.js 文件 >>> 引入接口文件import api from '@/api/api'const app = createApp(App)app.config.globalProperties.$api = api
-
组件内调用
import { ref, onMounted, getCurrentInstance } from 'vue'
const { proxy } = getCurrentInstance()
const getTableData = async () => {const data = await proxy.$api.getTableData()tableData.value = data.tableData
}
onMounted(() => {getTableData()
})