触发 window.addEventListener('focus') 时未定义$refs


<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>

我想在用户每次进入我的应用时将焦点放在commandLine输入上。 不幸的是,当我尝试使用 $refs 来查找我的<input>对象时,它是空的。

我怀疑这是因为window.addEventListerer将我的函数放入不同的上下文中,因此this变量不代表我的组件。

什么是解决它的干净方法?

不要使用箭头函数定义方法。在箭头函数中,this 在词法上绑定,不会指向 Vue。

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

参见 VueJS:为什么"这个"没有定义?

我怀疑这是因为window.addEventListerer把我的函数 进入不同的上下文,所以这个变量不代表我的 元件。

Vue 将方法绑定到 Vue 对象,以便特定代码通常可以工作。但是,不能绑定箭头函数。因此,您的问题。

最新更新