简体   繁体   English

Vuejs 方法 ajax 调用组件上的其他方法

[英]Vuejs method ajax call other method on component

how to call another method inside jquery ajax?如何在 jquery ajax 中调用另一个方法?

methods : {
    calert(type,msg="",error=""){
        console.log("call me");
    },
    getData(){
        $.ajax({
            type: "GET",
            success: function(data){
                // error calert not found
                calert(true,"","asd");
            },
            error: function (error) {
                // also error calert not found
                this.calert(false,"",error);
            },
            complete: function(){
            },
            url: "/test",
        });
    },
}

i have try to using this.calert but it doesn't work, still error我已经尝试使用this.calert但它不起作用,仍然出错

You simply need to update your code to use arrow functions, as follows:您只需更新代码即可使用箭头函数,如下所示:

methods : {
    calert(type,msg="",error=""){
        console.log("call me");
    },
    getData(){
        $.ajax({
            type: "GET",
            success: (data) => {
                this.calert(true,"","asd");
            },
            error: (error) => {
                this.calert(false,"",error);
            },
            complete: (){
            },
            url: "/test",
        });
    },
}

Or alternatively, store a local reference to the method, like:或者,存储对该方法的本地引用,例如:

methods : {
    calert(type,msg="",error=""){
        console.log("call me");
    },
    getData(){
        const { calert } = this;

        $.ajax({
            type: "GET",
            success: function(data){
                // error calert not found
                calert(true,"","asd");
            },
            error: function (error) {
                // also error calert not found
                calert(false,"",error);
            },
            complete: function(){
            },
            url: "/test",
        });
    },
}

btw i found the solution, looks like little bit tricky using this顺便说一句,我找到了解决方案,使用这个看起来有点棘手

methods : {
    calert(type,msg="",error=""){
        console.log("call me");
    },
    getData(){
        let vm = this;
        $.ajax({
            type: "GET",
            success: function(data){
                // error calert not found
                vm.calert(true,"","asd");
            },
            error: function (error) {
                // also error calert not found
                vm.calert(false,"",error);
            },
            complete: function(){
            },
            url: "/test",
        });
    },
}

i store the this to variable and then i use the variable to call another methods.我将this存储到变量中,然后使用该变量调用其他方法。

Anyone have any solutions better than this?任何人都有比这更好的解决方案吗?

Thanks谢谢

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM