VueJS - model binding not working with inputs using jQuery plugins

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

The problem is that when I change the value of the input dob

using the DateTimePicker, VueJS doesn't bind to that. It only works if the user enters the input directly, which I am trying to avoid (to format the date correctly).

The entrance 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 Masked Input Plugin digitally, same result. It seems that Vue doesn't recognize anything other than simple text input to the input. However, this works - albeit a little 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;
            })
        });

      

+3


source to share


1 answer


UPDATE: Directives have changed a lot in Vue.js 2.0 - the solution there will include a component and v-model. This answer was for Vue.js <2.0.

Your solution is typical when using the v-model and no keystrokes involved. In situations like this, 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>

      

+6


source







All Articles