当前位置:首页 > VUE

vue实现接口连接

2026-03-08 00:07:44VUE

Vue 实现接口连接的方法

使用 Axios 发送 HTTP 请求

安装 Axios 依赖:

npm install axios

在 Vue 组件中引入并使用 Axios:

import axios from 'axios';

export default {
  methods: {
    fetchData() {
      axios.get('https://api.example.com/data')
        .then(response => {
          console.log(response.data);
        })
        .catch(error => {
          console.error(error);
        });
    }
  }
}

配置全局 Axios 实例

main.js 或单独配置文件中设置全局 Axios 默认值:

vue实现接口连接

import axios from 'axios';

axios.defaults.baseURL = 'https://api.example.com';
axios.defaults.headers.common['Authorization'] = 'Bearer token';
axios.defaults.timeout = 5000;

Vue.prototype.$http = axios;

使用 async/await 语法

在 Vue 组件方法中使用现代异步语法:

export default {
  methods: {
    async getData() {
      try {
        const response = await this.$http.get('/data');
        this.data = response.data;
      } catch (error) {
        this.error = error.message;
      }
    }
  }
}

处理跨域问题

vue.config.js 中配置代理:

vue实现接口连接

module.exports = {
  devServer: {
    proxy: {
      '/api': {
        target: 'http://localhost:3000',
        changeOrigin: true,
        pathRewrite: {
          '^/api': ''
        }
      }
    }
  }
}

封装 API 模块

创建 api.js 集中管理接口:

import axios from 'axios';

export default {
  getUsers() {
    return axios.get('/users');
  },
  createUser(data) {
    return axios.post('/users', data);
  }
}

使用 Vuex 管理接口状态

在 store 中处理异步操作:

const actions = {
  async fetchUsers({ commit }) {
    try {
      const response = await api.getUsers();
      commit('SET_USERS', response.data);
    } catch (error) {
      commit('SET_ERROR', error);
    }
  }
}

拦截器配置

添加请求和响应拦截器:

axios.interceptors.request.use(config => {
  config.headers['X-Requested-With'] = 'XMLHttpRequest';
  return config;
});

axios.interceptors.response.use(
  response => response,
  error => {
    if (error.response.status === 401) {
      router.push('/login');
    }
    return Promise.reject(error);
  }
);

标签: 接口vue
分享给朋友:

相关文章

vue实现同步

vue实现同步

Vue 实现同步的方法 在 Vue 中实现同步操作通常涉及数据绑定、状态管理和异步操作的处理。以下是几种常见的方法: 使用计算属性(Computed Properties) 计算属性基于响应式依赖进…

vue实现oauth

vue实现oauth

Vue 实现 OAuth 的步骤 安装必要的依赖 确保项目中安装了 axios 和 vue-router。OAuth 通常需要发送 HTTP 请求和处理路由跳转。 npm install axios…

vue实现watch

vue实现watch

监听数据变化 在Vue中,watch用于监听响应式数据的变化并执行回调函数。基本语法如下: watch: { propertyName(newValue, oldValue) { //…

vue实现ftp

vue实现ftp

Vue 中实现 FTP 功能 Vue 本身是一个前端框架,无法直接操作 FTP 协议(FTP 通常需要后端支持)。以下是两种常见实现方式: 前端与后端配合实现 FTP 前端通过 API 与后端通信,…

vue实现选择置顶

vue实现选择置顶

Vue 实现选择置顶功能 在 Vue 中实现选择置顶功能,可以通过操作数据数组或结合 CSS 样式来实现。以下是几种常见的实现方法: 数组排序法 通过操作数据数组,将被选中的项移动到数组首位: /…

vue路由实现iframe

vue路由实现iframe

在Vue中实现iframe嵌入可以通过路由配置和组件动态加载来完成。以下是具体实现方法: 路由配置 在Vue Router的路由配置中,通过component属性动态加载iframe组件。需要将目标…