Search code examples
javascriptjqueryvue.jsvuejs2components

Vuejs method ajax call other method on component


how to call another method inside 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


Solution

  • 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",
            });
        },
    }