V-model with datepicker input

六月ゝ 毕业季﹏ 提交于 2020-03-22 10:39:22

问题


Trying to build a component that works with daepicker and using v-model to bind the input value. But the input event does not appear to be firing and I can’t seem to figure out why. Here’s my component:

<div id="app">
    <datepicker v-model="date"></datepicker>
</div>

Vue.component('datepicker', {
        template: '<input type="text" class="form-control pull-right" placeholder="dd/mm/aaaa" autocomplete="off">',
        mounted: function() {
            $(this.$el).datepicker({
                autoclose: true,
                startView: 'years',
            }).on('changeDate', function(e) {
                this.$emit('input', e.format('dd/mm/yyyy'));
            });
        },
        destroyed: function () {
            $(this.$el).datepicker('destroy');
        }
    });

var app = new Vue({
    el: '#app',
    data: {
        date: '2018-03-01'
    }
})

In addition, the following error appears in the console:

Uncaught TypeError: this.$emit is not a function


回答1:


If you're mixing jQuery and Vue (just a guess from the code fragment), you're mixing up your contexts. One (of many) ways to fix:

   mounted: function() {
        const self = this;
        $(this.$el).datepicker({
            autoclose: true,
            startView: 'years',
        }).on('changeDate', function(e) {
            self.$emit('input', e.format('dd/mm/yyyy'));
        });
    },



回答2:


I failed with jacky's answer, but thanks to https://github.com/Xelia, problem sovled (even in Vue 1.0, using ready life cycle instead of mounted)

Manually update vue data in datepicker changeDate event listener, like this

var app = new Vue({
  el: '#app',
  data: {
    startDate: '',
  },
  mounted() {
    $("#startDate").datepicker().on(
      "changeDate", () => {this.startDate = $('#startDate').val()}
    );
  },
})

https://jsfiddle.net/3a2055ub/

And by the way, if you are working on legacy company project using ES5 function instead of ES6 fat arrow function. Need to bind this, which is vue instance, into the function. For example:

mounted() {
  var self = this; // the vue instance
  $("#startDate").datepicker().on(
    "changeDate", function() {self.startDate = $('#startDate').val()}
  );
},

Of course there are other ways to reach this goal, as this blog written by Jason Arnold shows.

Reference: https://github.com/vuejs/vue/issues/4231

Probable related question: v-model not working with bootstrap datepicker



来源:https://stackoverflow.com/questions/50957334/v-model-with-datepicker-input

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