Vue---- Vue 3.x 中全局配置axios


vue 3.x 中全局配置 axios

0 安装 axios

npm i axios

1. 为什么要全局配置 axios

在实际项目开发中,几乎每个组件中都会用到 axios 发起数据请求。

此时会遇到如下两个问题:

① 每个组件中都需要导入 axios(代码臃肿)
② 每次发请求都需要填写完整的请求路径(不利于后期的维护)

在这里插入图片描述

2. 如何全局配置 axios

在 main.js 入口文件中,通过 app.config.globalProperties全局挂载 axios。

import { createApp } from 'vue'
// import App from './App.vue'
// import App from './components/myEvent/App.vue'
// import App from './components/v-model/App.vue'
// import App from './components/watch/App.vue'
// import App from './components/live/App.vue'
// import App from './components/fatherSon/App.vue'
// import App from './components/brother/App.vue'
import App from './components/grand/App.vue'


// 导入axios
import axios from 'axios'

import './index.css'

// 创建 Vue 实例对象
const app = createApp(App)
// 设置 axios 的请求根路径
axios.defaults.baseURL = 'https://www.escook.cn'
// 将 axios 挂载为 app 的全局自定义属性
// 每个组件可以通过 this 直接访问到全局挂载的自定义属性
app.config.globalProperties.$http = axios

app.mount('#app')

3. 发起get请求

<template>
  <div>
    <h1>App 组件</h1>
    <hr>
    <button @click="get">发起get请求</button>
  </div>
</template>

<script>
export default {
  name: 'App',
  methods: {
    async get() {
      // axios 返回的为 Promise 对象
      // 对返回的对象进行解构,获取其中的 data
      // 第一个参数为请求的路径,第二次参数为请求携带的数据
      const { data: res } = await this.$http.get( '/api/get', {
        params: {
          name: 'zs',
          age: 33
        }
      } )
      console.log( res )
    }
  }
}
</script>

<style>

</style>

请添加图片描述
请添加图片描述

4. 发起post请求

<template>
  <div>
    <h1>App 组件</h1>
    <hr>
    <button @click="get">发起get请求</button>
    <button @click="post">发起post请求</button>
  </div>
</template>

<script>
export default {
  name: 'App',
  methods: {
    async get() {
      // axios 返回的为 Promise 对象
      // 对返回的对象进行解构,获取其中的 data
      // 第一个参数为请求的路径,第二次参数为请求携带的数据
      const { data: res } = await this.$http.get( '/api/get', {
        params: {
          name: 'zs',
          age: 33
        }
      } )
      console.log( res )
    },
    async post() {
      // 第一个参数为请求地址
      // 第二个参数为请求携带的数据
      const { data: res } = await this.$http.post( '/api/post', {
        name: 'zs',
        gender: '男'
      } )
      console.log(res)
    }
  }
}
</script>

<style>

</style>

请添加图片描述
请添加图片描述

  • 1
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值