首页  >  问答  >  正文

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

我尝试使用 this.calert 但它不起作用,仍然错误

P粉316423089P粉316423089241 天前422

全部回复(2)我来回复

  • P粉281089485

    P粉2810894852024-02-22 11:46:37

    顺便说一句,我找到了解决方案,使用这个看起来有点棘手

    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 存储到变量中,然后使用该变量调用其他方法。

    有人有比这更好的解决方案吗?

    谢谢

    回复
    0
  • P粉491421413

    P粉4914214132024-02-22 11:36:54

    您只需更新代码即可使用箭头函数,如下所示:

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

    回复
    0
  • 取消回复