5

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;
    })
});
1
  • I'm having to do this same thing with my DatePicker. There is a set method like so: vm.$set(keypath, value). It does the same thing as vm.$data.keypath = value, but is just a bit cleaner. More here: vuejs.org/api/instance-methods.html Commented Jun 7, 2015 at 14:06

1 Answer 1

8

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>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.