vue3中全局配置axios

18 篇文章 0 订阅
17 篇文章 6 订阅

vue 3 中全局配置 axios

1. 为什么要全局配置 axios

在实际项目开发中,几乎每个组件中都会用到 axios 发起数据请求。此时会遇到如下两个问题:

① 每个组件中都需要导入 axios(代码臃肿)

② 每次发请求都需要填写完整的请求路径(不利于后期的维护)

在这里插入图片描述

2. 如何全局配置 axios

在 main.js 入口文件中,通过 app.config.globalProperties 全局挂载 axios,示例代码如下:

在这里插入图片描述

下面我们来实际操作 post 请求:

// main.js

import { createApp } from 'vue'
import App from './App.vue'
// import App from './components/zujian/app.vue'
import axios from 'axios'

import './index.css'

const app = createApp(App)

// 给 axios 设置请求根路径
axios.defaults.baseURL = 'https://www.escook.cn'

// 全局挂载 axios
app.config.globalProperties.$http = axios

app.mount('#app')

// 组件中具体请求代码

<template>
  <button @click="addpost">发起post请求</button>
</template>

<script>
export default {
  methods: {
    async addpost(){
      const {data:res} = await this.$http.post('/api/post',{name:'zs',age:20})
      console.log(res)
    }
  },

}
</script>

请求结果如图:

在这里插入图片描述

下面是 get 请求:

<template>
  <button @click="addpost">发起post请求</button>
  <button @click="addget">发起get请求</button>
</template>

<script>
export default {
  methods: {
    async addpost(){
      const {data:res} = await this.$http.post('/api/post',{name:'zs',age:20})
      console.log(res)
    },
    async addget(){
      const {data:res} = await this.$http.get('/api/get',{
        prams:{
          name:'ls',
          age:80
        }
      })
      console.log(res)
    }
  },

}
</script>

返回结果:

在这里插入图片描述

写在最后

✨个人笔记博客✨

星月前端博客
http://blog.yhxweb.top/

✨原创不易,还希望各位大佬支持一下

👍 点赞,你的认可是我创作的动力!

⭐️ 收藏,你的青睐是我努力的方向!

✏️评论,你的意见是我进步的财富!

  • 17
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 19
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 19
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

星月前端

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值