前言
在项目开发中,几乎每个组件都会用到 axios 发起数据请求。如果每个组件都要导入 axios 并且在请求时填写完整的请求路径,不仅使得代码变得臃肿同时也不利于后期的维护。
因此,我们需要全局配置 axios 。
如何全局配置 axios 呢 ?
在 main.js 入口文件中,通过 app.config.globalProperties 全局挂载 axios 。
import axios from 'axios'const app = createApp(App)// 配置请求的根路径axios.defaults.baseURL = ''// 将 axios 挂载为 app 的全局自定义属性( 如 $http )app.config.globalProperties.$http = axios
注意:这里的$http
是你自己自定义的属性,你也可以定义为$axios
、axios
等等。
如何使用 axios 发起请求呢 ?
发起 GET 请求示例:
<template><div><button type="button" class="btn btn-primary" @click="getInfo">发起 GET 请求</button></div></template><script>export default {methods: {async getInfo() {const {data: res } = await this.$http.get('/api/get', {params: {name: 'ls',age: 33}})console.log(res)}}}</script>
发起 POST 请求示例:
<template><div><button type="button" class="btn btn-success" @click="postInfo">发起 POST 请求</button></div></template><script>export default {methods: {async postInfo() {const {data: res } = await this.$http.post('/api/post', {name: 'zs', age: 20 })console.log(res)}}}</script>
点击按钮请求后结果展示: