在Vue中传递回调函数为何未丢失上下文?技术疑问
this get lost when passing this.escapeKeyListener to document.addEventListener? Great question! This behavior makes total sense once you understand how Vue handles methods under the hood. Here's the breakdown:
Vue automatically binds
thisto methods in themethodsoption
When your component initializes, Vue iterates over every method defined in themethodsobject and usesFunction.prototype.bind()to permanently tie the method'sthiscontext to the component instance. This means no matter how you reference or pass the method—even as a callback to a global event listener likedocument.addEventListener—thisinside the method will always point to your Vue component instance.Let's break down your specific code
YourescapeKeyListeneris defined in themethodsblock, so Vue has already bound itsthisto the component. When thekeyupevent fires on the document, the method is called with the correct context:this.closeCurrenciesPopup()correctly references the component's method, andthis.showCurrenciesPopup = falseupdates the component's data as expected.What would happen without Vue's automatic binding?
If you defined the function outside ofmethods(like directly in thecreatedhook without manual binding), you'd hit the classicthisloss issue:created() { // This would break because `this` would point to the document, not the component document.addEventListener('keyup', function(event) { if (event.keyCode === 27) { this.closeCurrenciesPopup(); // Error: closeCurrenciesPopup is not a function } }); }To fix that, you'd have to manually bind
thisor use an arrow function—but Vue saves you from that extra work for methods.
In short: Vue takes care of binding this to your methods automatically, so you don't have to worry about context loss when passing them as callbacks.
内容的提问来源于stack exchange,提问作者Rodion Golovushkin

