vue-resource使用

本文介绍了一个HTTP请求插件vue-resource的使用方法,并提供了GET、POST、JSONP等请求方式的示例代码。同时,还展示了如何设置全局拦截器以及安装和引入该插件的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

vue-resource是一个http请求插件,遵循promise,类似jquery中ajax操作。 vue-resource已不被官方推荐,官方推荐axios插件来操作http协议。

vue-resource中提供的方法
get(url, [options])
head(url, [options])
delete(url, [options])
jsonp(url, [options])
post(url, [body], [options])
put(url, [body], [options])
patch(url, [body], [options])
github源地址:https://github.com/pagekit/vue-resource/blob/master/README.md

安装vue-resource

npm i vue-resource -S

vue-resource是发布后也需要使用的,安装时要保存到dependencies中。
vue-resource引入
main.js中

import Vue from 'vue'
import App from './App'
import router from './router'
import VueResource from 'vue-resource'

Vue.config.productionTip = false
Vue.use(VueResource)

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  template: '<App/>',
  components: { App }
})

vue-resource使用
熟悉promise语法的话,使用vue-resource挺简单的,实际上任何不明确的地方看vue-resource文档即可,列一下最常用的get、post、jsonp以及全局拦截器的示例,方便查看。

get、post、jsonp示例

export default {
  name: 'app',
  data () {
    return {
      addr: '/data.json'
    }
  },
  methods: {
    dataGet () {
      console.info('get')
      this.$http.get(this.addr, {
        params: {
          name: '1'
        },
        headers: {
          token: 'a'
        }
      }).then(res => {
        console.info(res.data)
      }, error => {
        console.info(error)
      })
    },
    dataPost () {
      console.info('post')
      this.$http.post(this.addr, {
        name: '1'
      }, {
        headers: {
          token: 'a'
        }
      }).then(res => {
        console.info(res.data)
      }, error => {
        console.info(error)
      })
    },
    dataJsonP () {
      console.info('jsonp')
      this.$http.jsonp(this.addr, {
        params: {
          name: '1'
        }
      }).then(res => {
        console.info(res.data)
      }, error => {
        console.info(error)
      })
    }
  }
}

全局拦截器

main.js中

Vue.http.interceptors.push(function (request, next) {
  console.info('resquest 开始,这里可以写一些请求之前的预处理')
  next(function (response) {
    console.info('response 开始,所有http请求前都会调用此方法')
    return response
  })
})

vue-resource总结的很全面的几篇文章:
https://www.cnblogs.com/axl234/p/5899137.html
http://blog.youkuaiyun.com/wcslb/article/details/55057010
https://segmentfault.com/a/1190000007087934

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值