Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue 2 Datepicker Component

I am attempting to create a Vue 2 component using Bootstrap Datepicker but am getting stuck trying to update the input after a date is selected, here is my code:

Vue.component('datepicker', {
template: '\
  <input class="form-control datepicker"\
        ref="input"\
        v-bind:value="value"\
        v-on:input="updateValue($event.target.value)"\
        v-on:blur="updateValue($event.target.value)"\
        v-on:focus="updateValue($event.target.value)"\
        data-date-format="dd-mm-yyyy"\
        data-date-end-date="0d"\
        placeholder="dd-mm-yyyy"\
       type="text"  />\
',
props: {
    value: {
      type: String,
      default: moment().format('DD-MM-YYYY')
    }
},
mounted: function () {

},
methods: {
    updateValue: function (value) {
        this.$emit('input', value);
    },
}
});

The value updates fine if inputted via a keyboard but not when selected in the calendar. Any ideas how I can get the value updated on date changes via the calendar?

** Update **

I have gotten the following code working:

mounted: function() {
    let self = this;
    this.$nextTick(function() {
        $('.datepicker').datepicker({
            startView: 1,
            todayHighlight: true,
            todayBtn: "linked",
            autoclose: true,
            format: "dd-mm-yyyy"
        })
        .on('changeDate', function(e) {
            var date = e.format('dd-mm-yyyy');
            self.updateValue(date);
        });
    });
}

But it now updates the value of all the instances of Datepicker on the page. How can I set it up so it only updates for the selected Datepicker?

like image 986
Pedro Avatar asked Jan 05 '23 05:01

Pedro


1 Answers

Here is the final working component:

Vue.component('datepicker', {
template: '\
  <input class="form-control datepicker"\
        ref="input"\
        v-bind:value="value"\
        v-on:input="updateValue($event.target.value)"\
        data-date-format="dd-mm-yyyy"\
        data-date-end-date="0d"\
        placeholder="dd-mm-yyyy"\
        type="text"  />\
',
props: {
    value: {
      type: String,
      default: moment().format('DD-MM-YYYY')
    }
},
mounted: function() {
    let self = this;
    this.$nextTick(function() {
        $(this.$el).datepicker({
            startView: 1,
            todayHighlight: true,
            todayBtn: "linked",
            autoclose: true,
            format: "dd-mm-yyyy"
        })
        .on('changeDate', function(e) {
            var date = e.format('dd-mm-yyyy');
            self.updateValue(date);
        });
    });
},
methods: {
    updateValue: function (value) {
        this.$emit('input', value);
    },
}
});
like image 140
Pedro Avatar answered Jan 10 '23 13:01

Pedro