检查元素是否有焦点 - Vue.js 指令

Check if an element has focus - Vue.js directive

我正在尝试检查一个元素是否具有焦点,在我的例子中是输入,然后将 class 添加到另一个元素。 这就是我正在尝试的,但我不确定为什么 hasFocus() 不起作用。

onFocus () {
    let isFocused = document.el.querySelector('a-input')
    let focusedEl = document.el.querySelector('a-button')

    if(isFocused.hasFocus()) {
      focusedEl.classList.add('testClass')
    }
  }

我正在尝试在 Vue.js 自定义指令中执行此操作。

有一个 suggestion in the Vue.js forum to use the focusin 事件:

created() {
  document.addEventListener('focusin', this.focusChanged)
},
beforeDestroy() {
  document.removeEventListener('focusin', this.focusChanged)
},
methods: {
  focusChanged (event) {
    const el = event.target
    // do something with the element.
  }
}

因为我提到我需要将其作为自定义指令:

我就是这样修复的。

class someClassName {
  constructor (el, config = {}) {
    this.el = el
    this.input = el.querySelector('.a-input')
    this.button = el.querySelector('.a-button')

    this.onInputFocus = this.onInputFocus.bind(this)

    this.attachEvents()
  }

  onInputFocus () {
    this.button.classList.add('testclass')
  }

  attachEvents () {
    this.input.addEventListener('focus', this.onInputFocus)
  }
}