[Vuejs]-$refs is undefined when window.addEventListener('focus') is being fired

2đź‘Ť

âś…

Do not define methods with arrow functions. In arrow functions this is bound lexically and will not point to the Vue.

methods: {
  pageFocused(){
    console.log('pageFocused')
    console.log(this)
    this.$refs.commandLine.focus()
  }
}

See VueJS: why is “this” undefined?

I suspect that it’s because window.addEventListerer puts my function
into different context, so this variable doesn’t represent my
component.

Vue binds methods to the Vue object, so that particular code will work typically. You cannot however, bind an arrow function. Thus, your issue.

👤Bert

Leave a comment