Programmatically set focus on button in Vuetify

I am trying to focus the action buttons in a v-dialog every time it is opened. I tried using autofocus however it only works once.

Normally in Vuetify you can set the focus on an element by adding a reference and then calling the focus() function like this:

<v-text-field ref="refToElement" />

Code:

this.$nextTick(() => this.$refs.refToElement.focus())

However for v-btn this doesn't seem to work. How can I use javascript to focus the v-btn every time the dialog is shown?


Solution 1:

To set the focus on a v-btn you can add $el after the reference. For example

this.$nextTick(() => this.$refs.refToElement.$el.focus())

Full codepen of dialog and focused button: https://codepen.io/cby016/pen/eQXoBo.

Edit: For Vuetify 2.x try this

watch: {
  dialog () {
    if (!this.dialog) return
    requestAnimationFrame(() => {
      this.$refs.refToElement.$el.focus()
    })
  }
},

Solution 2:

For Vuetify 2.x use setTimeout:

setTimeout(() => {
  this.$refs.button.$el.focus()
})