当前位置:首页 > 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 请求

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

通过 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 语法

更现代的异步处理方式:

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

vue实现get请求

标签: vueget
分享给朋友:

相关文章

js实现vue

js实现vue

Vue.js 的基本实现方法 在 JavaScript 中实现 Vue.js 的功能,可以通过直接引入 Vue 库或使用现代构建工具(如 Vite 或 Webpack)。以下是几种常见的实现方式:…

vue grid实现

vue grid实现

Vue Grid 实现方法 在 Vue 中实现网格布局可以通过多种方式完成,包括使用原生 CSS Grid、第三方组件库或自定义组件。以下是几种常见方法: 使用原生 CSS Grid 通过 Vue…

vue筛选实现

vue筛选实现

Vue 筛选实现方法 使用计算属性实现筛选 计算属性是 Vue 中实现数据筛选的常用方式。通过定义一个计算属性,可以根据输入的条件动态过滤数据。 <template> <di…

vue实现定位

vue实现定位

Vue 中实现定位的方法 在 Vue 中实现定位可以通过以下几种方式: 使用 CSS 定位 通过 CSS 的 position 属性实现定位,Vue 中可以直接在组件的 <style>…

vue tab实现

vue tab实现

Vue Tab 实现方法 使用动态组件实现 Tab 在 Vue 中可以通过动态组件 <component :is="currentTab"> 结合 v-for 和 v-bind 实现 Ta…

vue实现vnc

vue实现vnc

Vue 实现 VNC 客户端 在 Vue 项目中实现 VNC 客户端功能,可以通过集成现有的 VNC 客户端库或组件完成。以下是具体实现方法: 安装依赖库 使用 noVNC 或其他 VNC 客…