Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 295
cby016 Avatar asked Dec 03 '18 16:12

cby016


1 Answers

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()
    })
  }
},
like image 87
cby016 Avatar answered Oct 11 '22 23:10

cby016