NightMICU - 9 months ago 195
HTML Question

VueJS - model binding not working with inputs using jQuery plugins

I am working on converting a form to utilize VueJS. The form has an input for a date of birth that uses eonasdan/bootstrap-datetimepicker (http://eonasdan.github.io/bootstrap-datetimepicker/).

The problem is that when I change the value of the

dob
input with DateTimePicker, VueJS does not bind to this. It only works if the user directly types in the input, which is what I'm trying to avoid (to properly format the date).

The input itself is nothing special:

    <div class="input-group date">
<input id="dob"
v-model="newCamper.dob"
placeholder="MM-DD-YYYY"
class="form-control"
name="dob" type="text">
<span class="glyphicon glyphicon-calendar"></span>
</span>
</div>


UPDATE

I also tried this with digitalbrush Masked Input Plugin, same result. It seems that anything other than just plain typing in an input is not recognized by Vue. However, this works - although it's a bit clunky:

$(document).ready(function () { var dob =$("#dob");
dob.change(function() {
var value = $(this).val(); vm.$data.newCamper.dob = value;
})
});


UPDATE: Directives have changed pretty dramatically in Vue.js 2.0. This answer pertained to Vue.js < 2.0.

Your solution is typical when v-model is used and keystrokes are not involved. In situations like this, in order to make it reusable, I usually write a directive:

Vue.directive("date", {
"twoWay": true,
"bind": function () {
var self = this;

$(self.el).mask(self.mask, { placeholder:"MM/DD/YYYY" });$(self.el).change(function() {
var value = $(this).val(); self.set(value); }); }, "unbind": function () { var self = this;$(self.el).unmask(self.mask);
}
});


And use it like this:

<div class="input-group date">
<input id="dob"
v-date="newCamper.dob"
placeholder="MM-DD-YYYY"
class="form-control"
name="dob" type="text">