关于箭头函数的 this 绑定

来源:互联网 发布:手机拍照滤镜软件 编辑:程序博客网 时间:2024/06/05 19:00

问题是怎么产生的

测试箭头函数在不同情景下的使用,当测试到Vue内生命周期调用计时器时,使用箭头函数渲染,普通函数不渲染,代码:

<template>  <div class="container">    <div :class="{'style1': this.styleType == 1, 'style2': this.styleType == 2}">测试箭头函数</div>  </div></template><script>export default {  name: 'class3',  data () {    return {      styleType: 1    }  },  created () {    setTimeout(function () { // 使用setTimeout(()=> {this.styleType = 2},2000),2秒后页面渲染会改变,使用function不会。      this.styleType = 2    }, 2000)  }}</script><style lang="less" scoped>.style1{  font-size: 20px;  color: red;}.style2{  font-size: 40px;  color: green;}</style>


原因在于:

setTimeout是window对象的方法,非严格模式下,当使用window对象方法调用function的时候,它的this会指向调用它的window。箭头函数的this指向当前上下文,所以会指向我们的Vue实例对象。而触发Vue的VM层动态渲染是Vue的实例。
除了箭头函数外,解决办法有几种,比如:

1. 定义局部的 this,让他指向上下文。
created () {    let _this = this  //指定 _this 指向上下文    setTimeout(function () {      _this.styleType = 2    }, 2000)  }

2. 如果我们会频繁更改这个 ‘styleType’ ,那么就将它定义在 methods 上下文当中,在 setTimeout 中调用。
created () {    setTimeout(this.setStyleType, 2000)  },  methods: {    setStyleType () {  //状态可多次调用,如果还有更多状态,可以考虑传参      this.styleType = 2    }  }




原创粉丝点击