[Vuejs]-$emit does not work from an anonymous function

3👍

The function keyword creates a new context for this. To use this keyword inside a function, you can either bind it, assign it to another variable such as var self = this or use an arrow function which does not create a new context.

window.onkeydown = evt => 
{ 
  evt = evt || window.event;
  var isEscape = false;
  if ("key" in evt) {
    isEscape = evt.key === "Escape" || evt.key === "Esc";
  } else {
    isEscape = evt.keyCode === 27;
  }

  if (isEscape) {
    this.$emit("close");
  }
};

Leave a comment