Vue中this的为undefined的问题

694 阅读1分钟

一、Vue官网methods中的this

methods 将被混入到 Vue 实例中。可以直接通过 VM 实例访问这些方法,或者在指令表达式中使用。方法中的 this 自动绑定为 Vue 实例
因此我们可以再methods中的函数上使用this去访问Vue实例data中的数据

二、methods中的函数相互调用

add: function () {
     this.n += 2;
   },
   change() {
     console.log("我是change调用了add和arrowFunction");
     this.add();
     this.arrowFunction();
   },
   arrowFunction: () => {
     alert("箭头函数");
     console.log("我是箭头函数");
   },

如上函数A在其内部调用函数B无论是普通函数还是箭头函数都是没有问题的this的指向也都是Vue的实例

arrow: () => {
     console.log("我是arrow");
     //箭头函数里面使用this ,this为undefined
     this.add();
     //立即执行函数里通过this进行调用也是undefined
     (function () {
       this.add();
       console.log("我是立即执行函数");
     })();
   },

如上在箭头函数内调用this时,因为箭头函数没有自己的this,因此为undefined,立即执行函数是相对封闭的因此this的作用域在该函数内部,因此也是undefined

三、解决方案

当遇到上述的this为undefined的情况可以采用如下的方式来改变

let _this = this

通过赋值的方式将this的值给 _this 确保this是确定的不是由调用的时候产生的