Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to focus v-textarea programatically in vuetify and typescript?

Seems like impossible now, I tried some crazy stuff like:

(this.refs.vtextarea as any).textarea.focus()

((this.refs.vtextarea as Vue).$el as HTMLElement).focus()

etc...

Javascript source is hardly readable for me but it's sad to had to do it like this...

Int this some basic stuff, or am I missing something obvious ?

PS: well I see textarea element somewhere there in hierarchy... Maybe I can access by some basic dom child element access way... but this will be like writing worst code of my life.

like image 567
Renetik Avatar asked Nov 29 '22 21:11

Renetik


2 Answers

Vuetify does not always work when focusing input, even with $nextTick.

This is how we do it generically for both input and textarea. We actually use this code with the ref set to our form in order to focus the first visible textarea or input. However, you can target just the widget that suits your needs.

mounted() {
  this.$nextTick(() => {
          const theElement = this.$refs.myRef         
          const input = theElement.querySelector('input:not([type=hidden]),textarea:not([type=hidden])')
          if (input) {
            setTimeout(() => {
              input.focus()
            }, 0)
          }
  });
}

The delay for $nextTick and setTimeout is negligible, often required, and will save you time and time again.

You don't need to exclude type=hidden either, but it can't hurt.

If the ref is not an HTMLElement, but instead a VueComponent, you may need to use this.$refs.myRef.$el to get the DOM element.

like image 178
Steven Spungin Avatar answered Feb 01 '23 07:02

Steven Spungin


I got mine to work with this:

mounted() {
    this.$nextTick(() => {
      setTimeout(() => {
        this.$refs.descriptionDescription.$refs.input.focus()
      })
    })
  },

Combination of code from @Thomas and @Steven Spungin

like image 23
DokiCRO Avatar answered Feb 01 '23 07:02

DokiCRO