In the development of vue, you will encounter a function nested in another function in the methods method, and the innermost function this cannot get data data. How to solve it?

One, the problem

In the methods method of vue, the two functions are nested with each other, and the innermost function this cannot get data data

insert image description here


Second, the reason

The pointing problem of this


Three, the solution

(1) Reassign the outermost function this to a variable

 methods: {
    /** 给最外层函数this重新赋值 */
    t3() {
      console.log('函数外',this.msgData);   // codekey
      let _this = this
      let t4 = function() {
      console.log('函数内',_this.msgData);   // codekey
      }
      t4()
    }
 }

insert image description here

(2) Use arrow functions

 methods: {
    /** 箭头函数 */
   t5() {
      console.log('函数外',this.msgData);   // codekey
      let t6 = () => {
        console.log('函数内',this.msgData);  // codekey
      }
      t6()
    }
  }

insert image description here


Guess you like

Origin blog.csdn.net/weixin_46243043/article/details/128239062