我正在尝试使用Bootstrap Datepicker创建一个Vue 2组件,但是在选择日期后我试图更新输入,这是我的代码:
Vue.component('datepicker', {
template: '\
<input class="form-control datepicker"\
ref="input"\
v-bind:value="value"\
v-on:input="updateValue($event.target.value)"\
v-on:blur="updateValue($event.target.value)"\
v-on:focus="updateValue($event.target.value)"\
data-date-format="dd-mm-yyyy"\
data-date-end-date="0d"\
placeholder="dd-mm-yyyy"\
type="text" />\
',
props: {
value: {
type: String,
default: moment().format('DD-MM-YYYY')
}
},
mounted: function () {
},
methods: {
updateValue: function (value) {
this.$emit('input', value);
},
}
});
如果通过键盘输入,则值更新正常,但在日历中选择时则不会更新。有关如何通过日历更改日期更新值的任何想法?
**更新**
我已经得到以下代码:
mounted: function() {
let self = this;
this.$nextTick(function() {
$('.datepicker').datepicker({
startView: 1,
todayHighlight: true,
todayBtn: "linked",
autoclose: true,
format: "dd-mm-yyyy"
})
.on('changeDate', function(e) {
var date = e.format('dd-mm-yyyy');
self.updateValue(date);
});
});
}
但它现在更新了页面上所有Datepicker实例的值。如何设置它以便仅更新所选的Datepicker?
答案 0 :(得分:8)
以下是最终的工作组成部分:
Vue.component('datepicker', {
template: '\
<input class="form-control datepicker"\
ref="input"\
v-bind:value="value"\
v-on:input="updateValue($event.target.value)"\
data-date-format="dd-mm-yyyy"\
data-date-end-date="0d"\
placeholder="dd-mm-yyyy"\
type="text" />\
',
props: {
value: {
type: String,
default: moment().format('DD-MM-YYYY')
}
},
mounted: function() {
let self = this;
this.$nextTick(function() {
$(this.$el).datepicker({
startView: 1,
todayHighlight: true,
todayBtn: "linked",
autoclose: true,
format: "dd-mm-yyyy"
})
.on('changeDate', function(e) {
var date = e.format('dd-mm-yyyy');
self.updateValue(date);
});
});
},
methods: {
updateValue: function (value) {
this.$emit('input', value);
},
}
});
答案 1 :(得分:1)
初始化Datepicker时,您可以在选项中指定选择项目时应调用的方法:
mounted: function() {
let self = this;
let args = {
format: 'DD-MM-YYYY',
placeholder: 'dd-mm-yyyy',
onSelect: function(dateText) {
self.updateValue(dateText);
}
};
this.$nextTick(function() {
$('.datepicker').datepicker(args)
});
}
答案 2 :(得分:0)
这样你就不会被所选日期覆盖,你也不会丢失你用
写的文字this.$nextTick(function() {
$(this.$el).datepicker(args).on('changeDate', function(e:any) {
var date = e.format(format);
var sval:string = e.currentTarget.__vue__.$refs.input._value;
//console.log(sval);
//so that value doesnt get erased everytime i put one character there, wait to have more
if(sval.length>2){
self.updateValue(date); console.log('upate'+date+sval);
}
}).on('hide', function(e:any) {
var date = e.format(format);
var sval:string = e.currentTarget.__vue__.$refs.input._value;
self.updateValue(date); console.log('upate2'+date+sval);
});
});