Vuejs method ajax calls other methods on component
P粉316423089
P粉316423089 2024-02-21 12:57:36
0
2
452

How to call another method in 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 tried using this.calert but it doesn't work, still error

P粉316423089
P粉316423089

reply all(2)
P粉281089485

BTW I found the solution, it looks a bit tricky to use 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 this into a variable and then use that variable to call other methods.

Does anyone have a better solution than this?

Thanks

P粉491421413

You can simply 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",
        });
    },
}

Alternatively, store a local reference to the method, for example:

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",
        });
    },
}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template