vue中方法相互调用

2022-12-30 08:29:44

vue中method方法相互调用,该方法不存在

method方法相互调用一般都会是this.functionName() 原本以为是没有任何问题的,但是方法与方法之间的调用就会出幺蛾子。

网上其它博客上说的
调用的时候使用

this.$options.methods.test2(); 
或者是
this.$options.methods.test2.bind(this)(); 

我试了无效,可能是用的地方不对吧!

例如method中有三个函数 A() 、B()、 C()

  • 一般的简单调用 ,两两之间相互调用,A()调用B(), A()调用C()
 methods: {
       onSubmit(formName) {
            //直接调用是没有问题的,此时的this指向的是vue
             this.myMessage();
        },
        myMessage() {
              this.$message({
                  showClose: true,
                  message: '恭喜你,这是一条成功消息',
                  type: 'success'
              });
            },
}
  • 相对复杂情况 A()调用B(),B函数中又调用了C函数(A调用了B,B中调用的又有C)

在这里插入图片描述

  • 正确的方式就是将this保存或者形参传递

在这里插入图片描述
这样看是不是简单很多,代码就放在下面自己研究一下

  • 相同的代码,这种情况就不行了,在另外一个函数 tj()
 methods: {
       onSubmit(formName) {
  /
          坑的起点就在这。
          this.tj();
 //
        },
        myMessage() {
              this.$message({
                  showClose: true,
                  message: '恭喜你,这是一条成功消息',
                  type: 'success'
              });
            },
         tj() {
                axios.post('../system/systemMenu', this.form)
                .then(function (response) {
                
                这样浏览器会提示你  myMessage()没有被发现
               	问题就出现在this  此时的this指向已经不在是vue了,此时的方法就不能被this调用	
               	所以解决办法就是将this保存下来,并且按照参数的形式传递给调用函数
                    this.myMessage();
                ///    
                    console.log(response);
                })
                .catch(function (error) {
                    console.log(error);
                });
            },
}
  • 问题就出现在this的指向问题,正确的解决办法:
methods: {
       onSubmit(formName) {
            /
            //直接调用是没有问题的,此时的this指向的是vue
                     this.myMessage();
             //
            //解决办法,将this以形参的形式传递给函数
                    this.tj(this);
        },
        myMessage() {
              this.$message({
                  showClose: true,
                  message: '恭喜你,这是一条成功消息',
                  type: 'success'
              });
            },
         tj(obj) {
                axios.post('../system/systemMenu', this.form)
                .then(function (response) {
                
                //此时的obj就是this,这个this指向的是vue,所以就能正确调用myMessage()方法
                    obj.myMessage();
                ///    
                    console.log(response);
                })
                .catch(function (error) {
                    console.log(error);
                });
            },
}
  • 作者:蹦跑的蜗牛
  • 原文链接:https://blog.csdn.net/qq_43356920/article/details/106886267
    更新时间:2022-12-30 08:29:44