How to set onfocus on datepicker vue material?

785 views Asked by At

I'm trying to write a function to be executed when the datepicker get focus, but I don't know how.

Here is my page code:

<div class="md-layout-item md-small-size-100 md-size-22">
    <md-datepicker v-model="birthDate" :md-open-on-focus="false" ref="birthDateEl">
        <label>Birth date</label>
    </md-datepicker>
</div>

I got a working code, but I think that this is not the better solution:

mounted(){

    this.$refs.birthDateEl.$refs.input.$el.onfocus = function() {
        this.onBirthDateFocus("some param");
      };
},

A good solution should be put "onfocus" in the template code.

1

There are 1 answers

4
user14967413 On BEST ANSWER

You should be able to listen to focusin event on <md-datepicker>, because it bubbles up the element tree (unlike focus event). You should also use .native modifier, which is required when listening to native events on a custom component.

In the event handler function, you should probably check that the event was fired on the exact input which represents the datepicker.

Template:

<md-datepicker @focusin.native="onBirthDateFocus($event)" ...>

Script:

methods: {
  onBirthDateFocus(event) {
    if (event.target.id === 'datePickerInput') {
      /*...*/
    }
  }
}