当前位置:首页 > 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 默认值:

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 中配置代理:

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);
    }
  }
}

拦截器配置

添加请求和响应拦截器:

vue实现接口连接

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中实现导航切换内容,可以通过以下方式实现: 使用动态组件 动态组件通过<component :is="currentComponent">实现内容切…

vue 实现toast

vue 实现toast

vue 实现 toast 的方法 在 Vue 中实现 Toast 提示功能可以通过多种方式,以下是几种常见的实现方法: 使用第三方库 Vue 生态中有许多成熟的 Toast 库,例如 vue-toa…

vue 实现grid

vue 实现grid

在Vue中实现Grid布局可以通过多种方式完成,以下是几种常见的方法: 使用CSS Grid布局 CSS Grid是一种强大的布局系统,可以直接在Vue组件的样式中使用。以下是一个简单的示例: &…

vue实现tag

vue实现tag

Vue 实现标签(Tag)功能 在 Vue 中实现标签(Tag)功能可以通过多种方式完成,以下是一些常见的方法和实现步骤: 使用动态组件和 v-for 通过 v-for 指令动态渲染标签列表,结合样…

vue实现公告

vue实现公告

Vue 实现公告功能的方法 公告功能通常需要实现滚动展示、自动切换或固定显示的效果。以下是几种常见的实现方式: 使用 marquee 标签实现滚动公告 <template> <…

vue实现试卷

vue实现试卷

Vue实现试卷系统的基本思路 使用Vue.js构建试卷系统需要结合组件化开发、状态管理和后端数据交互。核心功能包括题目展示、答题逻辑、计时器和提交答案。 核心功能模块划分 试卷组件结构 试卷容器组…