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.csdn.net/wcslb/article/details/55057010
https://segmentfault.com/a/1190000007087934