bootstrap-datetimepicker with vue.js not working properly

我的未来我决定 提交于 2019-12-05 10:53:46

I couldn't find a better way than losing focus (blur).

Here's my code:

Vue.component('picker', {
    'props': ['date'],
    'template': '\
        <div class="form-group">\
            <div class="input-group date datepicker">\
                <input type="text" class="form-control" :value="this.date" v-on:focus="datepick_dialog_open" v-on:blur="select_by_lose_focus">\
                <span class="input-group-addon">\
                    <span class="glyphicon glyphicon-calendar"></span>\
                </span>\
            </div>\
        </div>',
    'mounted': function() {
        $(this.$el.firstChild).datetimepicker();
    },
    'methods': {
        'datepick_dialog_open': function() {
            this.$el.firstChild.children[1].click();
        },
        'select_by_lose_focus': function() {
            console.log('AHOY!');
            this.date = this.$el.firstChild.firstChild.value;
        }
    }
});

app = new Vue({
    'el': '#app',
    'data': {}
});

The point is, you really can't use it if your element does not lose focus. It updates the data when input loses its focus. IDK any better way.

v-on:focus is irrelevant. It just opens the datetime picker UI when input gains focus.

The main job is done by select_by_lose_focus.

Another example using $emit and v-model on the component. This page describes why value and $emit are needed to support v-model. I needed a form element name and optional required class for validation.

https://vuejs.org/v2/guide/components.html#Form-Input-Components-using-Custom-Events

  <picker name="start_date_1_1" required="1" v-model="res.start_date"></picker>

  Vue.component('picker', {
    props: ['name', 'value', 'required'],
    template: '\
      <div class="form-group">\
          <div class="input-group date">\
              <input :name="name" type="text" class="form-control" v-bind:class="{required: required}"  v-bind:value="value">\
              <span class="input-group-addon">\
                  <span class="glyphicon glyphicon-calendar"></span>\
              </span>\
          </div>\
      </div>',
    mounted: function() {
      var self = this;
      var picker = $(this.$el.firstChild).datepicker({autoclose: true});
      picker.on('changeDate', function(e) {
        self.$emit('input', e.date.toLocaleDateString("en-US", {day: '2-digit', month: '2-digit', year: 'numeric'}));
      });
    }
  });
mikez

Thanks for the answer @nejdetckenobi, if picking date only, the blur approach works. However, if picking both date & time, I found that the blur approach didn't work so well.

Instead I followed the Vue.js wrapper component example. It makes use of on('change', function(){}) and $emit.

The code below that worked for me (in my setup) with date formatting, a key part is in mounted section of your vue component declaration.

Vue.component('datetime', {
  props: ['value'],
  template: '<input class="form-control" id="override-datetime-field"></input>',
  mounted: function () {
    var vm = this
    $(this.$el)
      .datetimepicker()
      .val(this.value === '' ? '' : moment(this.value).format('DD-MMM-YYYY, h:mm a'))
      .trigger('change')
      .on('change', function () {
        vm.$emit('input', this.value)
      })
  },
  watch: {
    value: function (value) {
      $(this.$el).val(value).trigger('change');
    }
  }
} 

The key part is here:

$(an-element).datetimepicker().trigger('change')
.on('change', function () {
  vm.$emit('input', this.value)
})

Original source example: https://vuejs.org/v2/examples/select2.html

Got it to work by dispatching the input Event upon changing the date.

$('.with-calendar').datetimepicker({
    weekStart: 1,
    language: 'de',
    bootcssVer: 3,
    format: "yyyy-mm-dd hh:ii:00",
    viewformat: "yyyy-mm-dd hh:ii:00",
    autoclose: true
}).on('changeDate', function (event) { // Communicate datetimepicker result to vue
    let inputFields = event.target.getElementsByTagName('input'); // depends on your html structure
    for (let i = 0; i < inputFields.length; i++) {
        inputFields[i].dispatchEvent(new Event('input', {'bubbles': true}));
    }
});
<template>
...
<div class="form-group">
    <label class="col-sm-3 control-label">Date and Time</label>
    <div class="col-sm-6">
        <div class="input-group date with-calendar">
            <input type="text" class="form-control" v-model="start_datetime"/>
            <span class="input-group-addon">
                <span class="glyphicon glyphicon-calendar"></span>
            </span>
        </div>
    </div>
</div>
...
</template>

got this problem and got it to work by initializing the date-picker after initializing the vue. e.g:

var vm = new Vue({
    el: '#myForm',
    data: {
        field1: "",
        field2: ""
    }
});

$(".date-picker").datepicker({
    todayHighlight: true,
    autoclose: true,
    closeOnDateSelect: true
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!