Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[vue] 你有封装过axios吗?主要是封装哪方面的? #303

Open
haizhilin2013 opened this issue Jun 20, 2019 · 4 comments
Open
Labels
vue vue

Comments

@haizhilin2013
Copy link
Collaborator

[vue] 你有封装过axios吗?主要是封装哪方面的?

@haizhilin2013 haizhilin2013 added the vue vue label Jun 20, 2019
@zhixiaotong
Copy link

统一上下文请求路径、统一超时时间、统一错误处理和拦截发送请求用于添加token

@luuman
Copy link

luuman commented Oct 23, 2019

封装处理配置(路径、时间、token)、统一管理接口、错误处理、不同形式的请求、消息提示、loading等。

@crush2020
Copy link

crush2020 commented Jan 19, 2021

用Promise在封装一次axios,并统一baseURL,超时时间,请求拦截,响应拦截处理,统一管理接口,批量导出。

@Cai-zhiji
Copy link

如何封装axios

  1. 创建模块
    在项目中创建一个axios.js文件,然后在该文件中引入Axios,并配置全局的默认请求选项。
// axios.js
import axios from 'axios';

// 设置默认请求配置
axios.defaults.baseURL = 'http://api.example.com';

export default axios;

在需要使用Axios的地方,可以直接引入axios.js文件并使用它发送请求。

import axios from './axios';

axios.get('/api/user')
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    console.error(error);
  });
  1. 创建插件
    创建一个名为axiosPlugin.js的插件文件,使用Vue的插件机制来封装Axios。
// axiosPlugin.js
import axios from 'axios';

const axiosPlugin = {
  install(Vue) {
    Vue.prototype.$axios = axios;
  }
};

export default axiosPlugin;

在Vue应用的入口文件中,通过Vue.use()方法安装插件。

import Vue from 'vue';
import axiosPlugin from './axiosPlugin';

Vue.use(axiosPlugin);

new Vue({
  // ...
}).$mount('#app');

然后,在组件中就可以通过this.$axios来使用Axios发送请求。

export default {
  mounted() {
    this.$axios.get('/api/user')
      .then(response => {
        console.log(response.data);
      })
      .catch(error => {
        console.error(error);
      });
  }
}

通过以上方式,可以在Vue中封装Axios,使其在项目中更方便地使用。在模块化的方式中,直接引入axios.js文件即可使用Axios,而在插件方式中,则可以通过this.$axios在Vue实例和组件中使用Axios。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
vue vue
Projects
None yet
Development

No branches or pull requests

5 participants