vue-resource 是 Vue.js 的一个官方 HTTP 客户端插件(Vue 1.x/2.x 时期),用于处理 AJAX 请求。虽然现在已被 axios 取代,但了解它仍有历史意义。

1. 核心功能概览

功能 说明 现代替代
HTTP 请求 封装 XMLHttpRequest axios/fetch
Vue 集成 深度集成 Vue 响应式系统 @vue/composition-api
拦截器 请求/响应拦截 axios 拦截器
Promise 支持 基于 Promise 的 API 原生 Promise/axios

2. 基本使用方法

安装配置

# 安装(历史版本)
npm install vue-resource
// main.js
import Vue from 'vue'
import VueResource from 'vue-resource'

Vue.use(VueResource) // 全局注册

组件中使用

<template>
  <div>
    <button @click="getData">获取数据</button>
    <div v-if="loading">加载中...</div>
    <div v-else>{{ userData }}</div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      loading: false,
      userData: null
    }
  },
  methods: {
    getData() {
      this.loading = true

      // 使用 this.$http(vue-resource 注入的方法)
      this.$http.get('/api/user/123')
        .then(response => {
          this.userData = response.body
        })
        .catch(error => {
          console.error('请求失败:', error)
        })
        .finally(() => {
          this.loading = false
        })
    }
  }
}
</script>

3. 主要特性详解

3.1 请求方法

// GET 请求
this.$http.get('/api/users')
  .then(response => console.log(response.body))

// POST 请求  
this.$http.post('/api/users', { name: 'John' })
  .then(response => console.log('创建成功'))

// PUT、DELETE、PATCH 等
this.$http.put('/api/users/1', { name: 'Jane' })
this.$http.delete('/api/users/1')

3.2 全局配置

// 请求默认配置
Vue.http.options.root = '/api'
Vue.http.headers.common['Authorization'] = 'Bearer token123'
Vue.http.interceptors.push(...) // 拦截器

3.3 响应处理

this.$http.get('/api/data').then(response => {
  console.log(response.body)     // 响应体
  console.log(response.status)  // 状态码
  console.log(response.headers) // 响应头
})

4. 与现代 axios 的对比

特性 vue-resource axios
Vue 集成 ✅ 深度集成 ⚠️ 需手动配置
API 设计 Vue 风格 标准 HTTP 客户端
维护状态 ❌ 已废弃 ✅ 活跃维护
功能完整性 基础功能 功能丰富
TypeScript ❌ 支持差 ✅ 完整支持

5. 迁移到 axios 的示例

vue-resource 代码

// 旧的 vue-resource 写法
export default {
  methods: {
    fetchUser() {
      this.$http.get('/api/user/1')
        .then(response => this.user = response.body)
    }
  }
}

等效的 axios 代码

// 现代 axios 写法
import axios from 'axios'

export default {
  methods: {
    async fetchUser() {
      try {
        const response = await axios.get('/api/user/1')
        this.user = response.data
      } catch (error) {
        console.error('请求失败:', error)
      }
    }
  }
}

6. 为什么被废弃?

技术原因

  1. 功能有限:相比 axios 功能较少
  2. 维护停滞:Vue 团队转向维护核心库
  3. 标准统一:axios 成为社区标准
  4. Tree-shaking:独立的 axios 更利于打包优化

官方推荐迁移

// Vue 2 官方建议:
import axios from 'axios'

// 全局配置
Vue.prototype.$http = axios

// 组件中使用
this.$http.get('/api/data')

7. 历史版本参考

vue-resource 的辉煌时期

// 2016-2017 年的典型用法
new Vue({
  el: '#app',
  data: { posts: [] },
  created() {
    // 生命周期中自动获取数据
    this.$http.get('/api/posts')
      .then(response => this.posts = response.data)
  }
})

拦截器示例(历史代码)

// 请求拦截器
Vue.http.interceptors.push((request, next) => {
  // 显示加载状态
  this.$root.$emit('loading-start')

  next(response => {
    // 隐藏加载状态
    this.$root.$emit('loading-complete')
  })
})

8. 学习价值

了解演进历史

  • jQuery.ajaxvue-resourceaxios/fetch
  • 理解前端 HTTP 客户端的发展历程

概念延续

  • 拦截器、请求/响应转换等概念被 axios 继承
  • Vue 3 的 Composition API 提供类似集成模式

总结

vue-resource 是 Vue 生态发展过程中的一个重要里程碑

  • 历史价值:简化了 Vue 1.x/2.x 的 HTTP 请求
  • 教育意义:展示了 Vue 插件系统的设计思路
  • 生产环境不再推荐使用,应迁移到 axios
  • 🔄 替代方案:使用 axios + Vue 3 Composition API

当前建议:新项目直接使用 axios,老项目逐步迁移到 axios