Vue2 与 Vue3 全局引入 Axios 的详细教程

Vue.js 是一个用于构建用户界面的渐进式 JavaScript 框架,而 Axios 是一个基于 Promise 的 HTTP 客户端,常用于与后端服务器进行数据交互。在实际项目中,我们通常需要全局引入 Axios 以便在各个组件中方便地进行 HTTP 请求。本文将详细介绍如何在 Vue2 和 Vue3 项目中全局引入 Axios,并逐步讲解每一部分的代码。

Vue2 全局引入 Axios

1. 安装 Axios

首先,使用 npm 或 yarn 安装 Axios:

npm install axios

或者

yarn add axios

2. 配置 Axios

在 Vue2 项目的入口文件 main.js 中配置 Axios:

// main.js

import Vue from 'vue';
import App from './App.vue';
import axios from 'axios';

Vue.config.productionTip = false;

// 将 axios 挂载到 Vue 原型上,这样在任何组件中都可以通过 this.$axios 访问
Vue.prototype.$axios = axios;

new Vue({
  render: h => h(App),
}).$mount('#app');

代码详解:

  • import Vue from 'vue';:引入 Vue 库。
  • import App from './App.vue';:引入根组件 App。
  • import axios from 'axios';:引入 Axios 库。
  • Vue.config.productionTip = false;:关闭生产提示。
  • Vue.prototype.$axios = axios;:将 Axios 挂载到 Vue 原型上,使得在所有 Vue 实例中都可以通过 this.$axios 访问 Axios。
  • new Vue({ render: h => h(App), }).$mount('#app');:创建 Vue 实例,并将其挂载到 id 为 #app 的元素上。

3. 使用 Axios

在任何 Vue 组件中都可以通过 this.$axios 使用 Axios。例如:

<template>
  <div>
    <h1>{{ title }}</h1>
  </div>
</template>

<script>
export default {
  data() {
    return {
      title: ''
    };
  },
  created() {
    // 使用 this.$axios 发起 GET 请求
    this.$axios.get('https://jsonplaceholder.typicode.com/posts/1')
      .then(response => {
        // 将响应数据赋值给 title
        this.title = response.data.title;
      })
      .catch(error => {
        console.log(error);
      });
  }
};
</script>

代码详解:

  • data() { return { title: '' }; }:定义组件的数据,初始化 title 为空字符串。
  • created():Vue 生命周期钩子,组件创建完成时调用。
  • this.$axios.get('https://jsonplaceholder.typicode.com/posts/1'):通过 Axios 发起 GET 请求。
  • then(response => { this.title = response.data.title; }):请求成功后,将响应数据中的 title 赋值给组件的 title
  • catch(error => { console.log(error); }):请求失败时,打印错误信息。

Vue3 全局引入 Axios

1. 安装 Axios

和 Vue2 一样,首先安装 Axios:

npm install axios

或者

yarn add axios

2. 配置 Axios

在 Vue3 项目的入口文件 main.js 中配置 Axios:

// main.js

import { createApp } from 'vue';
import App from './App.vue';
import axios from 'axios';

// 创建 Vue 应用实例
const app = createApp(App);

// 将 axios 挂载到应用实例的全局属性上,这样在任何组件中都可以通过 this.$axios 访问
app.config.globalProperties.$axios = axios;

// 挂载应用实例
app.mount('#app');

代码详解:

  • import { createApp } from 'vue';:引入 Vue 的 createApp 函数。
  • import App from './App.vue';:引入根组件 App。
  • import axios from 'axios';:引入 Axios 库。
  • const app = createApp(App);:创建 Vue 应用实例。
  • app.config.globalProperties.$axios = axios;:将 Axios 挂载到应用实例的全局属性上,使得在所有组件中都可以通过 this.$axios 访问 Axios。
  • app.mount('#app');:将应用实例挂载到 id 为 #app 的元素上。

3. 使用 Axios

在任何 Vue3 组件中都可以通过 this.$axios 使用 Axios。例如:

<template>
  <div>
    <h1>{{ title }}</h1>
  </div>
</template>

<script>
export default {
  data() {
    return {
      title: ''
    };
  },
  created() {
    // 使用 this.$axios 发起 GET 请求
    this.$axios.get('https://jsonplaceholder.typicode.com/posts/1')
      .then(response => {
        // 将响应数据赋值给 title
        this.title = response.data.title;
      })
      .catch(error => {
        console.log(error);
      });
  }
};
</script>

代码详解:

  • data() { return { title: '' }; }:定义组件的数据,初始化 title 为空字符串。
  • created():Vue 生命周期钩子,组件创建完成时调用。
  • this.$axios.get('https://jsonplaceholder.typicode.com/posts/1'):通过 Axios 发起 GET 请求。
  • then(response => { this.title = response.data.title; }):请求成功后,将响应数据中的 title 赋值给组件的 title
  • catch(error => { console.log(error); }):请求失败时,打印错误信息。

总结

本文详细介绍了在 Vue2 和 Vue3 项目中全局引入 Axios 的方法和步骤。在 Vue2 中,我们通过将 Axios 挂载到 Vue 原型上实现全局引入;在 Vue3 中,则是通过将 Axios 挂载到应用实例的全局属性上实现全局引入。通过这种方式,我们可以方便地在项目的任何组件中使用 Axios 进行 HTTP 请求,简化了代码编写和维护。希望本文对你在 Vue 项目中使用 Axios 有所帮助。

Vue3中,取消了使用Vue.prototype来挂载全局方法和属性。取而代之的是使用官方提供的globalPropertiesAPI来实现全局挂载。你可以按照以下步骤在Vue3中全局引入axios: 1.首先,安装axios。可以使用以下命令进行安装: ``` npm install axios ``` 或 ``` yarn add axios ``` 或 ``` pnpm install axios ``` 2.然后在你的入口文件(main.js)中引入axios: ``` import { createApp } from 'vue'; import axios from 'axios'; const app = createApp(App); app.config.globalProperties.$http = axios; app.mount('#app'); ``` 通过app.config.globalProperties.$http = axios;这行代码将axios挂载到全局的$http属性上,使得在各个组件或页面中可以使用this.$http来请求接口。 这样,你就在Vue3中成功全局引入axios123 #### 引用[.reference_title] - *1* *3* [Vue3全局挂载使用axios](https://blog.csdn.net/C90283/article/details/123049450)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}} ] [.reference_item] - *2* [Vue3中全局配置 axios 的两种方式](https://blog.csdn.net/weixin_56650035/article/details/125610295)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}} ] [.reference_item] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

繁依Fanyi

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

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

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

打赏作者

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

抵扣说明:

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

余额充值