0
<template>
  <div>
    <input ref='commandLine' />
  </div>
</template>

<script>
export default {
  mounted () {
    window.addEventListener('focus', this.pageFocused)
  },
  methods: {
    pageFocused: () => {
      console.log('pageFocused')
      console.log(this)
      this.$refs.commandLine.focus()
    }
  }
}
</script>

I want to set focus on commandLine input every time user get into my app. Unfortunately, when I try to use $refs in order to find my <input> object, it's null.

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

What is a clean way to solve it?

Piotrek
  • 10,919
  • 18
  • 73
  • 136

1 Answers1

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
  • 80,741
  • 17
  • 199
  • 164