【问题标题】:binding ajax response to vue.js (multiple requests on single page)将 ajax 响应绑定到 vue.js(单个页面上的多个请求)
【发布时间】:2016-11-09 11:30:33
【问题描述】:

在研究 Vue.js 以及它如何与 laravel 交互几天后,我遇到了困难,我开始怀疑两件事:一是我的知识还不够好,无法继续我的愿望增强我们的一两个用户体验:不可能做我想做的事情,所以希望有更多知识的人可以帮助我克服我的障碍。

请原谅我相当基本的模型!

就 jquery / Ajax 而言,一切正常,但是我已经尝试转移到 vue.js,而那时事情运行并不顺利。

我的 Ajax 请求工作正常,但是当我使用 this.$set 或 this.$http 作为 get 或 post 请求时,我会收到以下消息:

11:14:28.690 TypeError: this.$http is undefined 1 vue:61:21
    window.onload/queryAPI http://me.dev/vue:61:21
    window.onload/ajaxVm<.methods.callAjax http://me.dev/vue:55:29
    n http://me.dev/newjs/vue.js:6:836
    G/< http://me.dev/newjs/vue.js:6:6272

11:24:21.000 TypeError: this.$set is not a function 1 vue:34:29
    window.onload/queryAPI/<.success http://me.dev/vue:34:29
    jQuery.Callbacks/fire http://code.jquery.com/jquery-3.1.1.js:3305:11
    jQuery.Callbacks/self.fireWith http://code.jquery.com/jquery-3.1.1.js:3435:7
    done http://code.jquery.com/jquery-3.1.1.js:9242:5
    .send/callback/< http://code.jquery.com/jquery-3.1.1.js:9484:9

我的完整测试文档:

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
    <script type="text/javascript" src="//code.jquery.com/jquery-3.1.1.js"></script>
    <script type="text/javascript" src="/newjs/vue.js"></script>

    <title>VueJS</title>
    <script type='text/javascript'>//<![CDATA[
        window.onload=function(){
            var ajaxVm = new Vue({
                el:'#test',
                data:{
                    User:{
                        Name: 'John Doe'
                    },
                    datas: 'Hi'
                },
                methods:{
                    callAjax: function(e){
                        queryAPI();
                    }
                }
            });

            var queryAPI = function(){
                this.$http.post('/vue/ajax', this.formData).then(function(response) {
                    console.log(response);
                }, function() {
                    console.log('failed');
                })
            }
        }
        </script>
    </head>
<body>
<div id="test">
    <label id="data">@{{datas}}</label>
    <label>@{{User.Name}}</label>
    <br/>
    <button v-on:click="callAjax">
        Call Ajax
    </button>
</div>
</body>
</html>

并且使用 ajax/jquery 作为 this.$http 的一个姿势,除了 this.$set 之外它工作正常,因为我必须恢复使用 jquery 来更新元素。

<!DOCTYPE html>
    <html>
    <head>
        <meta http-equiv="content-type" content="text/html; charset=UTF-8">
        <script type="text/javascript" src="//code.jquery.com/jquery-3.1.1.js"></script>
        <script type="text/javascript" src="/newjs/vue.js"></script>
        <title>VueJS</title>
        <script type='text/javascript'>//<![CDATA[
            window.onload=function(){
                var ajaxVm = new Vue({
                    el:'#test',
                    data:{
                        User:{
                            Name: 'John Doe'
                        },
                        datas: 'Hi'
                    },
                    methods:{
                        callAjax: function(e){
                            queryAPI();
                        }
                    }
                });

                var queryAPI = function(){
                    $.ajax({
                        url: '/vue/ajax',
                        type: 'POST',
                        dataType: 'json',
                        data:  ajaxVm.$data ,
                        success:function(data){
                            $('#data').html(data.Message);
                            console.log(data);
                            //this.$set('datas', data.Name)
                        },
                        error:function(xhr,text,exception){
                            console.error(exception);
                        }
                    })
                }
            }
        </script>
    </head>
<body>
<div id="test">
    <label id="data">@{{datas}}</label>
    <label>@{{User.Name}}</label>
    <br/>
    <button v-on:click="callAjax">
        Call Ajax
    </button>
</div>
</body>
</html>

我同时包含了 vue.js 2.0.5 和 vue-resource 1.0.3,我尝试使用带有 gulp 的 npm 到单个 .js 文件,我还尝试通过 cdn 单独包含它们,无论如何我这样做了我在使用 this.$http 或 this.$set 时仍然会出现错误,我开始怀疑它是否与 vue-resource 相关?有没有其他方法可以将我的 ajax 调用绑定到元素或组件,我不知道是什么,所以我无法让事情正常工作,一切似乎都被正确地放在一起,我已经阅读了无数其他 vuejs相关的问题,但是当您的知识很少时,一切都会受到限制。

谢谢,我将非常感谢您对此提出的任何建议,因为它让我发疯!

【问题讨论】:

    标签: jquery ajax laravel vue.js


    【解决方案1】:

    这看起来像是范围问题。使用this.$httpthis必须引用Vue实例,不能在Vue实例外调用$set$httpthis,所以你需要将你的ajax请求放在视图模型内:

    var ajaxVm = new Vue({
        el:'#test',
        data:{
            User:{
                Name: 'John Doe'
            },
            datas: 'Hi'
        },
        methods:{
            callAjax: function(e){
               // Now this refers to the Vue instance
               this.$http.post('my-url',this.data).then((response) => {
                    // Response logic here
               })
            }
        }
    });
    

    当您执行以下操作时,this 指的是封闭函数:

    var queryAPI = function(){
      //here this refers to queryAPI, not vue
    }
    

    要从视图模型外部调用$http,您需要直接引用 Vue 实例:

    var queryAPI = function(){
                    // Now we are calling $http from the "ajaxVm" vue model instance
                    ajaxVm.$http.post('/vue/ajax', this.formData).then(function(response) {
                        console.log(response);
                    }, function() {
                        console.log('failed');
                    })
                }
    

    还请记住,任何包装在函数中的东西都会创建它自己对this 的引用,除非您使用箭头函数(这些示例假定您已将代码放置在 Vue 实例中):

    this.$http.get('/foo').this(function(response){
          // here this only refers to the function, not the Vue instance
    });
    

    使用 ECMA6 中的箭头函数:

    this.$http.get('/foo').this((response) =>{
          // Because we used an arrow function, no new context is created
          // so this refers to the Vue instance
    });
    

    【讨论】:

    • 优秀的深度和教育答案,感谢您抽出时间提供这样的答案。我现在就试一试,看看我的运气在我的午休时间是否有所改变!再次感谢您。
    • 您对添加 ajaxVm 的建议。 $set 和 $http 都能立即工作,我想我花了 48 小时来忽略基本原理,因为我认为作为 vue.js 和 js 的新手通常会更复杂,所以我非常感谢,唯一的我面对克雷格的问题是你有没有在控制台中遇到过这个错误:TypeError: can't assign to properties of (new String("datas")): not an object。我尝试从 laravel 返回一个完整的用户对象,我尝试返回一个基本的 html 字符串和一个 json 对象,但在将其传递给 {{ datas }} 时失败
    • 如果你从 laravel 返回 json 那么只需要先解析它:var response = JSON.parse(response.body);
    猜你喜欢
    • 2015-12-01
    • 2015-10-30
    • 1970-01-01
    • 1970-01-01
    • 2019-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多