Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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="input-group-addon">
      <span class="glyphicon glyphicon-calendar"></span>
    </span>
</div>

UPDATE

I also tried this with digitalbrush Masked Input Plugin, the 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.mask("99/99/9999",{placeholder:"MM/DD/YYYY"});
    dob.change(function() 
       var value = $(this).val();
       vm.$data.newCamper.dob = value;
    })
});
like image 804
NightMICU Avatar asked Jun 06 '15 22:06

NightMICU


1 Answers

UPDATE: Directives have changed pretty dramatically in Vue.js 2.0 - the solution there would involve a component and v-model. 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.mask = "99/99/9999";
        $(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">
        <span class="input-group-addon">
            <span class="glyphicon glyphicon-calendar"></span>
        </span>
</div>
like image 65
David K. Hess Avatar answered Nov 15 '22 03:11

David K. Hess