当前位置:首页 > VUE

vue实现get请求

2026-02-17 18:57:24VUE

使用 axios 发送 GET 请求

在 Vue 项目中,通常使用 axios 库发送 HTTP 请求。以下是实现 GET 请求的步骤:

安装 axios 依赖:

npm install axios

在 Vue 组件中引入并使用:

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 fetching data:', error);
        });
    }
  }
}

使用 Vue 生命周期钩子发送 GET 请求

可以在 createdmounted 钩子中自动触发请求:

export default {
  data() {
    return {
      items: []
    };
  },
  created() {
    axios.get('https://api.example.com/items')
      .then(response => {
        this.items = response.data;
      });
  }
}

带参数的 GET 请求

传递查询参数有两种方式:

vue实现get请求

通过 URL 直接拼接:

axios.get('https://api.example.com/search?keyword=vue')

通过 params 配置项:

axios.get('https://api.example.com/search', {
  params: {
    keyword: 'vue',
    page: 1
  }
})

使用 async/await 语法

更现代的异步处理方式:

vue实现get请求

export default {
  methods: {
    async loadUser() {
      try {
        const response = await axios.get('/api/user/123');
        this.user = response.data;
      } catch (error) {
        console.error('Failed to load user:', error);
      }
    }
  }
}

全局配置 axios

可以在 main.js 中设置默认配置:

import axios from 'axios';

axios.defaults.baseURL = 'https://api.example.com';
axios.defaults.timeout = 5000;

Vue.prototype.$http = axios;

之后在组件中可以直接使用:

this.$http.get('/data')

拦截器配置

添加请求和响应拦截器:

axios.interceptors.request.use(config => {
  config.headers.Authorization = 'Bearer token';
  return config;
});

axios.interceptors.response.use(
  response => response,
  error => {
    if (error.response.status === 401) {
      // 处理未授权情况
    }
    return Promise.reject(error);
  }
);

标签: vueget
分享给朋友:

相关文章

vue实现截图

vue实现截图

Vue 实现截图的方法 使用 html2canvas 库 安装 html2canvas 库: npm install html2canvas 在 Vue 组件中使用: import html2ca…

vue实现socket

vue实现socket

Vue 中实现 WebSocket 通信 在 Vue 项目中实现 WebSocket 通信可以通过原生 WebSocket API 或第三方库(如 socket.io-client)完成。以下是两种常…

vue实现handsontable

vue实现handsontable

Vue 中实现 Handsontable 要在 Vue 项目中集成 Handsontable,可以使用官方提供的 @handsontable/vue 封装库。以下是一个完整的实现步骤。 安装依赖 确…

vue实现表白

vue实现表白

Vue 实现表白页面 使用 Vue 可以快速创建一个动态、交互式的表白页面。以下是一个简单的实现方案: 基础结构 创建一个 Vue 项目或单文件组件,包含以下核心部分: <template&…

vue 实现视频

vue 实现视频

Vue 实现视频播放功能 使用 Vue 实现视频播放功能可以通过 HTML5 的 <video> 标签或第三方库(如 video.js)来实现。以下是两种常见的方法: 使用 HTML5…

vue实现select

vue实现select

Vue 实现 Select 组件的方法 在 Vue 中实现 Select 组件可以通过多种方式完成,以下是几种常见的方法: 使用原生 HTML select 元素 原生 HTML 的 <sel…