vue.jsvuejs2vue-material

How to set onfocus on datepicker vue material?


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.


Solution

  • 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') {
          /*...*/
        }
      }
    }