Reputation: 5311
I am trying to use bootstrap datepicker in Vue Js by adding it dynamically, but it is not initializing.
HTML
<div v-for="(aligner,index) in aligners" v-bind:key="aligner">
<input type="hidden" v-bind:name="'AlignerDetails[' + index + '].BatchNo'" v-bind:value="'AlignerDetails_' + (index + 1) + '__BatchNo'" />
<div class='mt-element-ribbon bg-grey-steel'>
<div class='ribbon ribbon-round ribbon-color-primary uppercase'>Batch #{{index + 1}}</div>
<div class='pull-right'>
<a href='javascript:;' v-on:click='remove(index);' class='btn-delete'>
<i class='fa fa-trash-o font-red'></i>
</a>
</div>
<div class='row ribbon-content'>
<div class='col-md-12 padding-left-0 padding-right-0' style="margin-bottom:5px;">
<input type="text" v-bind:name="'AlignerDetails[' + index + '].AlignersSent'" v-on:blur="calculate();" class="form-control alignersSent" placeholder="Aligners Sent" />
</div>
<div class='col-md-12 padding-left-0 padding-right-0'>
<div class="input-group date bs-datetime">
<input type="date" v-bind:name="'AlignerDetails[' + index + '].AlignersSentDate'" class="form-control form-control-inline alignersSentDate" placeholder="Aligners Sent Date" autocomplete="off" />
<span class="input-group-addon">
<button class="btn btn-default date-set" type="button">
<i class="fa fa-calendar"></i>
</button>
</span>
</div>
</div>
</div>
</div>
</div>
JS
var app = new Vue({
el: "#alignerDetails",
data: {
aligners: []
},
mounted: function () {
$('.date').datepicker({
autoclose: true,
format: 'dd M yyyy'
});
},
methods: {
add: function () {
this.aligners.push({});
},
remove: function (index) {
this.aligners.splice(index, 1);
}
}
});
I am not getting why this is not working..
Upvotes: 1
Views: 7157
Reputation: 1025
The trick I've found when embedding Jquery elements that require initialization is to place them inside a hidden element using v-if. According to Vuejs's documentation, v-if does not render that element until it meets the v-if condition. So the items are not in the DOM until you programatically set them to. At which case give you a great event to add jquery init statements.
Place your datepicker inside a v-if based div
<div v-if="show"></div>
Inside mounted I do something like this
async mounted() {
this.show = true
$('select', this.$el).selectpicker();
$('.datepicker', this.$el).datepicker({format: 'mm/dd/yyyy', orientation: 'bottom auto'});
//this is how you allow datepicker to send its value to v-model on the input field
$('.datepicker').change(function() {
$(this)[0].dispatchEvent(new Event('input'));
});
}
Upvotes: 4