当前位置:首页 > VUE

vue实现API调用

2026-02-19 18:29:04VUE

使用 Vue 实现 API 调用的方法

使用 Axios 进行 API 调用

安装 Axios 依赖:

npm install axios

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

import axios from 'axios';

export default {
  data() {
    return {
      posts: [],
      error: null
    };
  },
  methods: {
    async fetchPosts() {
      try {
        const response = await axios.get('https://jsonplaceholder.typicode.com/posts');
        this.posts = response.data;
      } catch (error) {
        this.error = error.message;
      }
    }
  },
  created() {
    this.fetchPosts();
  }
};

使用 Vue Resource(已废弃但可用)

安装 Vue Resource:

npm install vue-resource

在 main.js 中引入:

import Vue from 'vue';
import VueResource from 'vue-resource';

Vue.use(VueResource);

组件中使用:

vue实现API调用

export default {
  data() {
    return {
      users: []
    };
  },
  created() {
    this.$http.get('https://jsonplaceholder.typicode.com/users')
      .then(response => {
        this.users = response.body;
      });
  }
};

使用 Fetch API

直接使用浏览器原生 Fetch API:

export default {
  data() {
    return {
      todos: []
    };
  },
  methods: {
    fetchTodos() {
      fetch('https://jsonplaceholder.typicode.com/todos')
        .then(response => response.json())
        .then(data => {
          this.todos = data;
        });
    }
  },
  mounted() {
    this.fetchTodos();
  }
};

使用 async/await 语法

结合 async/await 使代码更清晰:

export default {
  data() {
    return {
      comments: []
    };
  },
  methods: {
    async getComments() {
      const response = await fetch('https://jsonplaceholder.typicode.com/comments');
      this.comments = await response.json();
    }
  },
  created() {
    this.getComments();
  }
};

配置全局 API 基础 URL

在 Axios 中配置全局基础 URL:

vue实现API调用

// 在 main.js 或单独配置文件中
axios.defaults.baseURL = 'https://api.example.com';
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;

处理 API 错误

完整的错误处理示例:

async fetchData() {
  try {
    const response = await axios.get('/endpoint');
    if (response.status !== 200) {
      throw new Error('Network response was not ok');
    }
    this.data = response.data;
  } catch (error) {
    console.error('Error fetching data:', error);
    this.error = 'Failed to load data. Please try again later.';
  }
}

使用 Vuex 管理 API 状态

在 Vuex store 中处理 API 调用:

// store.js
import axios from 'axios';

export default new Vuex.Store({
  state: {
    products: []
  },
  mutations: {
    SET_PRODUCTS(state, products) {
      state.products = products;
    }
  },
  actions: {
    async fetchProducts({ commit }) {
      const response = await axios.get('/api/products');
      commit('SET_PRODUCTS', response.data);
    }
  }
});

组件中使用 Vuex action:

export default {
  computed: {
    products() {
      return this.$store.state.products;
    }
  },
  created() {
    this.$store.dispatch('fetchProducts');
  }
};

使用拦截器

Axios 请求/响应拦截器示例:

// 请求拦截器
axios.interceptors.request.use(
  config => {
    // 在发送请求前做些什么
    config.headers['X-Custom-Header'] = 'foobar';
    return config;
  },
  error => {
    // 对请求错误做些什么
    return Promise.reject(error);
  }
);

// 响应拦截器
axios.interceptors.response.use(
  response => {
    // 对响应数据做点什么
    return response;
  },
  error => {
    // 对响应错误做点什么
    if (error.response.status === 401) {
      // 处理未授权情况
    }
    return Promise.reject(error);
  }
);

封装 API 服务

创建独立的 API 服务文件:

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

const apiClient = axios.create({
  baseURL: 'https://api.example.com',
  withCredentials: false,
  headers: {
    Accept: 'application/json',
    'Content-Type': 'application/json'
  }
});

export default {
  getPosts() {
    return apiClient.get('/posts');
  },
  createPost(post) {
    return apiClient.post('/posts', post);
  }
};

在组件中使用封装的服务:

import api from '@/services/api';

export default {
  data() {
    return {
      posts: []
    };
  },
  async created() {
    const response = await api.getPosts();
    this.posts = response.data;
  }
};

标签: vueAPI
分享给朋友:

相关文章

vue的艾特功能实现

vue的艾特功能实现

Vue 的 @ 功能实现 在 Vue 中实现类似社交平台的 @ 功能,通常涉及输入框的监听、用户匹配和选择插入。以下是具体实现方法: 监听输入框内容 使用 v-model 绑定输入框内容,并通过 @…

vue 实现表单

vue 实现表单

Vue 表单实现方法 Vue.js 提供了多种方式实现表单,包括双向数据绑定、表单验证和动态表单生成。以下是常见的实现方法: 基础表单绑定 使用 v-model 指令实现表单元素与数据的双向绑定:…

vue实现tip

vue实现tip

Vue实现Tooltip的方法 使用Vue实现Tooltip可以通过多种方式完成,以下是几种常见的方法: 使用原生HTML的title属性 在Vue模板中直接使用HTML的title属性是最简单的实…

vue逻辑实现怎么实现

vue逻辑实现怎么实现

Vue 逻辑实现方法 Vue 的逻辑实现主要通过组件化、响应式数据、计算属性、方法、生命周期钩子等方式完成。以下是一些核心实现方法: 数据驱动与响应式 在 Vue 中,通过 data 选项定义响应式…

vue如何实现mvvm

vue如何实现mvvm

Vue 实现 MVVM 的核心机制 Vue 的 MVVM(Model-View-ViewModel)实现依赖于数据绑定和响应式系统,通过以下核心机制完成: 数据劫持(响应式系统) Vue 使用 Ob…

vue实现登录拦截

vue实现登录拦截

实现登录拦截的方法 在Vue项目中,可以通过路由守卫(Navigation Guards)实现登录拦截,确保未登录用户无法访问受保护的路由。以下是具体实现方式: 使用全局前置守卫 在路由配置文件中(…