除了 vue-resource 之外,还可以使用 `axios` 的第三方包实现实现数据的请求( `axios`不支持跨域请求)
引入vue-resource
<script src="js/vue.js"></script>
<script src="js/vue-resource.js"></script>
基本语法
引入vue-resource后,可以基于全局的Vue对象使用http,也可以基于某个Vue实例使用http。
// 基于全局Vue对象使用http
Vue.http.get('/someUrl', [options]).then(successCallback, errorCallback);
Vue.http.post('/someUrl', [body], [options]).then(successCallback, errorCallback);
// 在一个Vue实例内使用$http
this.$http.get('/someUrl', [options]).then(successCallback, errorCallback);
this.$http.post('/someUrl', [body], [options]).then(successCallback, errorCallback);
在发送请求后,使用then
方法来处理响应结果,then
方法有两个参数,第一个参数是响应成功时的回调函数,第二个参数是响应失败时的回调函数。
then
方法的回调函数也有两种写法,第一种是传统的函数写法,第二种是更为简洁的ES 6的Lambda写法:
// 传统写法
this.$http.get('/someUrl', [options]).then(function(response){
// 响应成功回调
}, function(response){
// 响应错误回调
});
// Lambda写法
this.$http.get('/someUrl', [options]).then((response) => {
// 响应成功回调
}, (response) => {
// 响应错误回调
});