jquery - 在 Ajax 函数中访问 Vue.js 组件属性

标签 jquery ajax vue.js

以下代码引用了一个组件函数,该函数从 url 获取数据并尝试将该数据设置为属性。它不起作用,似乎 this 无法从 ajax clousure 范围访问。

var MyComp = Vue.extend({
props: {
        html_prop: {}
        ....
},
methods: {
        fetchCondiciones: function(url){

            $.ajax({
                    type: "GET",
                    url: url,
                    cache: false,
                    data: vardata ,
                    success: function(data,status,error) {
                        if( data!=''){
                            this.html_prop = data;
                        }
                    },
                    error: function(data,status,error){
                        alert(error);
                    }
            });

        }

        ...
    }
})

如何使this可访问?

最佳答案

您需要.bind this 上下文,因为在组件的上下文中不会自然地调用回调:

var MyComp = Vue.extend({
props: {
        html_prop: null,
},
        // ....
        fetchCondiciones: function(url){

            $.ajax({
                    type: "GET",
                    url: url,
                    cache: false,
                    data: vardata,
                    success: function(data,status,error) {
                        if(data != ''){
                            this.html_prop = data;
                        }
                    }.bind(this), // bind this here
                    error: function(data,status,error){
                        alert(error);
                    }.bind(this) // bind this here
            });

        }

        // ...
});

您可以在此处了解有关 .bind 的更多信息:https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_objects/Function/bind

关于jquery - 在 Ajax 函数中访问 Vue.js 组件属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37132872/

相关文章:

JQuery - 启用/禁用每行复选框

javascript - angularjs ng-重复错误: Duplicates in a repeater

javascript - 无法将带有变量的 id 添加到类中

laravel - v-on :change event for radio input VueJS

typescript - 属性 'use' 在类型 'typeof..., Property ' 上不存在扩展'在类型'typeof 上不存在

javascript - vuejs 在@click 事件中使用箭头函数

javascript - 当元素到达视口(viewport)顶部时添加类

python - 我怎样才能在 QueryDict 中获取我的参数?

javascript - 在两个字段上进行 JQuery Ajax 实时搜索 - 输入和选择

javascript - 使用 JQuery 在 AJAX 上成功迭代 JSON 数据