当前位置:首页 > VUE

vue+怎么实现api

2026-02-22 23:07:50VUE

实现 API 调用的基本方法

在 Vue 中实现 API 调用通常需要结合 HTTP 客户端库(如 axiosfetch)来完成。以下是常见的实现方式:

安装 axios

npm install axios

封装 API 请求

// src/api/index.js
import axios from 'axios';

const api = axios.create({
  baseURL: 'https://your-api-endpoint.com',
  timeout: 5000,
});

export const fetchData = (params) => api.get('/data', { params });
export const postData = (payload) => api.post('/data', payload);

在组件中调用 API

选项式 API 写法

<script>
import { fetchData } from '@/api';

export default {
  data() {
    return {
      items: [],
      loading: false,
    };
  },
  methods: {
    async loadItems() {
      this.loading = true;
      try {
        const response = await fetchData({ page: 1 });
        this.items = response.data;
      } catch (error) {
        console.error('API Error:', error);
      } finally {
        this.loading = false;
      }
    },
  },
  mounted() {
    this.loadItems();
  },
};
</script>

组合式 API 写法

<script setup>
import { ref, onMounted } from 'vue';
import { fetchData } from '@/api';

const items = ref([]);
const loading = ref(false);

const loadItems = async () => {
  loading.value = true;
  try {
    const response = await fetchData({ page: 1 });
    items.value = response.data;
  } catch (error) {
    console.error('API Error:', error);
  } finally {
    loading.value = false;
  }
};

onMounted(() => {
  loadItems();
});
</script>

使用环境变量管理 API 地址

创建 .env 文件

VUE_APP_API_BASE_URL=https://your-api-endpoint.com

修改 axios 配置

const api = axios.create({
  baseURL: process.env.VUE_APP_API_BASE_URL,
});

处理请求拦截和响应拦截

添加全局拦截器

// 请求拦截
api.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem('token');
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => Promise.reject(error)
);

// 响应拦截
api.interceptors.response.use(
  (response) => response.data,
  (error) => {
    if (error.response.status === 401) {
      // 处理未授权情况
    }
    return Promise.reject(error);
  }
);

使用 Vuex/Pinia 管理 API 状态

Pinia 示例

vue+怎么实现api

// stores/apiStore.js
import { defineStore } from 'pinia';
import { fetchData } from '@/api';

export const useApiStore = defineStore('api', {
  state: () => ({
    items: [],
    loading: false,
  }),
  actions: {
    async fetchItems() {
      this.loading = true;
      try {
        const data = await fetchData();
        this.items = data;
      } catch (error) {
        console.error(error);
      } finally {
        this.loading = false;
      }
    },
  },
});

这些方法涵盖了 Vue 中实现 API 调用的主要场景,包括基本请求、错误处理、状态管理等。根据项目复杂度可以选择适合的方案组合使用。

标签: vueapi
分享给朋友:

相关文章

vue 页签实现

vue 页签实现

Vue 页签实现方法 在 Vue 中实现页签功能通常涉及动态组件、路由或状态管理。以下是几种常见的实现方式: 使用动态组件 通过 Vue 的 <component> 动态组件结合 v-f…

vue 实现简单登陆

vue 实现简单登陆

以下是一个使用 Vue 3 实现的简单登录功能示例,包含表单验证和基础交互逻辑: 创建 Vue 组件 <template> <div class="login-contai…

vue实现图集

vue实现图集

Vue 实现图集的方法 在 Vue 中实现图集功能可以通过多种方式完成,以下是一些常见的方法和实现步骤。 使用第三方库(如 vue-image-lightbox) 安装 vue-image-ligh…

vue 实现弹幕

vue 实现弹幕

vue 实现弹幕的方法 使用 CSS 动画和动态渲染 在 Vue 中实现弹幕效果,可以通过动态渲染弹幕元素并结合 CSS 动画实现。以下是具体步骤: 数据准备 创建一个数组存储弹幕数据,每条弹幕包…

vue实现开关

vue实现开关

Vue 实现开关组件的方法 使用原生HTML和Vue数据绑定 通过v-model绑定复选框的checked状态,结合CSS样式实现开关效果: <template> <label…

vue实现分栏

vue实现分栏

Vue实现分栏的常见方法 使用CSS Flexbox布局 通过Flexbox可以快速实现分栏效果,适合大多数响应式布局场景 <template> <div class="con…