不灭的焱

革命尚未成功,同志仍须努力下载JDK17

作者:Albert.Wen  添加时间:2023-10-07 00:15:18  修改时间:2024-05-20 17:44:27  分类:前端/Vue/Node.js  编辑

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>

 

 

参考:

  1. https://blog.csdn.net/qq_61950936/article/details/126396941