Fe-interview: [vue] watch的属性用箭头函数定义结果会怎么样?

Created on 22 Jun 2019  ·  4Comments  ·  Source: haizlin/fe-interview

[vue] watch的属性用箭头函数定义结果会怎么样?

vue

Most helpful comment

因为箭头函数默绑定父级作用域的上下文,所以不会绑定vue实例,所以 this 是undefind

All 4 comments

this为undefined

this是undefined,要更改的属性会报TypeError错误, Cannot read property 'xxx' of undefined

因为箭头函数默绑定父级作用域的上下文,所以不会绑定vue实例,所以 this 是undefind

不应该使用箭头函数来定义 watcher 函数 (例如 searchQuery: newValue => this.updateAutocomplete(newValue))。理由是箭头函数绑定了父级作用域的上下文,所以 this 将不会按照期望指向 Vue 实例,this.updateAutocomplete 将是 undefined。

Was this page helpful?
0 / 5 - 0 ratings