Vuejs方法ajax呼叫元件上的其他方法
P粉316423089
P粉316423089 2024-02-21 12:57:36
0
2
529

如何在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",
        });
    },
}

我嘗試使用 this.calert 但它不起作用,仍然錯誤

P粉316423089
P粉316423089

全部回覆(2)
P粉281089485

順便說一句,我找到了解決方案,使用這個看起來有點棘手

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

我將 this 儲存到變數中,然後使用該變數呼叫其他方法。

有人有比這更好的解決方案嗎?

謝謝

P粉491421413

您只需更新程式碼即可使用箭頭函數,如下所示:

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

或者,儲存對該方法的本機引用,例如:

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",
        });
    },
}
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板