Vuejs方法ajax调用组件上的其他方法
P粉316423089
P粉316423089 2024-02-21 12:57:36
0
2
418

如何在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",
        });
    },
}
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!