2-11 vue-recource

2017-09-05  本文已影响10人  codeTao

vue-recource

vue-resource是Vue.js的一款插件,它可以通过XMLHttpRequest或JSONP发起请求并处理响应。也就是说,$.ajax能做的事情,vue-resource插件一样也能做到,而且vue-resource的API更为简洁。

基本语法

// 基于全局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);

this.$http.get('/someUrl', [options]).then(function(response){
// 响应成功回调
}, function(response){
// 响应错误回调
});

vue-resource 1.0

<script src="js/vue.js"></script>
<script src="js/vue-resource.js"></script>
<script>
    new Vue({
        el:'#app',
        methods:{
            get:function () {
                this.$http.get('get.php', {
                    a:1, b:1
                }).then(function (res) {
                    console.log(res.data);
                },function (error) {
                    console.log(error);
                })
            },

            //添加emulateJSON, 相当于设置请求头
            post:function () {
                var config = {
                    emulateJSON:true
                };

                this.$http.post('post.php', {
                    a:2, b:1
                }, config).then(function (res) {
                    console.log(res.data);
                },function (error) {
                    console.log(error);
                })
            },

        }

    })

</script>

vue-resource2.0

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<div id="app">
    
    <button @click="get()">get请求</button>
    <button @click="post()">post请求</button>
</div>

</body>

<script src="js/vue.js"></script>
<script src="js/vue-resource.js"></script>
<script>
    var vm = new Vue({
        el:'#app',
        methods:{
            
            get:function () {
                //vue-resource 1.3.4 和vue2.0 后get参数发生改变
                this.$http.get('get.php', {
                    params:{a:2, b:1}
                }).then(function (res) {
                    console.log(res.data);
                }, function (error) {
                    console.log(error);
                });
            },

            post:function () {
                var config = {
                    //添加emulateJSON 相当于设置请求头
                    emulateJSON:true
                };

                this.$http.post('post.php', {
                    a:2, b:1
                }, config).then(function (res) {
                    console.log(res.data);
                }, function (error) {
                    console.log(error);
                });
            }

        }
        
    });
    
    
</script>

</html>

上一篇下一篇

猜你喜欢

热点阅读