VueJS - model binding not working with inputs using jQuery plugins

喜夏-厌秋 提交于 2019-12-21 05:12:10

问题


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:


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>


来源:https://stackoverflow.com/questions/30688199/vuejs-model-binding-not-working-with-inputs-using-jquery-plugins

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!