关于箭头函数的 this 绑定

问题是怎么产生的

测试箭头函数在不同情景下的使用,当测试到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
    }
  }




  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值