关于箭头函数的 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 } }
阅读全文
1 0
- 关于箭头函数的 this 绑定
- ES6箭头函数中的this绑定问题
- bind(this)绑定this指向的对象、箭头函数和闭包
- JavaScript的this机制与箭头函数(一)——this绑定的4种机制
- es6箭头函数中this的问题
- JS-箭头函数中的this的指向
- 深入理解ES6箭头函数的this
- 箭头函数中的this
- JS的this总结(下)-ES6箭头函数this指向
- JavaScript的this机制与箭头函数(二)——箭头函数中的this
- ES6:箭头函数以及this
- ES6 箭头函数中的 this
- es6箭头函数this指向
- 关于ES6的箭头函数的详解
- 关于箭头函数的理解摘记
- 十,(补充)ES6中箭头函数this的指向
- Javascript箭头函数中的this指向错乱的解决办法
- 前端-浅谈箭头函数的this和普通函数的this
- 实习笔记1
- HDU2010 水仙花数
- android 使用zxing生成中间嵌套logo的二维码
- JqGrid选中行、取消选中行、获得选中行数据
- 第12讲 通过php程序添加数据
- 关于箭头函数的 this 绑定
- activeMQ启动错误 BeanFactory not initialized
- 剑指Offer_编程题 替换空格
- HBase架构
- 第13讲 通过php更新删除数据
- Tensorflow & Caffe 对比
- 高温硫化苯基硅橡胶生胶 IOTA-34
- 和高学历的差别
- Data Structure:stack