一、背景
在Vue項目中使用了第三方的datepicker插件,在選擇日期后vue無法檢測到datepicker輸入框的變化
``` <label class="fl">日期:</label> <div class="input-wrapper fr"> <input class="daterangepicker" ref="datepicker" v-model="dateRange"/> <a href="javascript:;"></a> </div> ```
export default {
data() {
return {
dateRange: ''
}
},
watch: {
dateRange(newVal, oldVal) {
console.log(newVal) // 選擇日期后無法監聽dateRange的改變
}
}
}
二、分析
查找資料發現:Vue實際上無法監聽由第三方插件所引起的數據變化。因此上面的方法是行不通的。但是,Vue給我們提供的一個方法,它可以將任意數據轉化為可以被Vue監聽到的數據,他就是:vm.$set。
三、解決
以我用到的datepicker為例(jquery-daterangepicker)
data() {
return {
date: '',
beginDate: '',
endDate: ''
}
},
mounted () {
$('.daterangepicker').dateRangePicker({
autoClose: true,
format: 'YYYY-MM-DD'
}).bind('datepicker-change', this.setDate) //插件自帶方法,選擇日期后觸發回調
},
methods: {
setDate() {
let datepicker = this.$refs.datepicker
//這一步是關鍵,具體說明可以參見vue api手冊
this.$set(this.date, 'beginDate', datepicker.value)
this.$set(this.date, 'endDate', datepicker.value)
this.beginDate = this.date.beginDate.slice(0, 11)
this.endDate = this.date.endDate.slice(-10)
}
},
watch: {
// 這里就可以監聽數據變化啦,可以愉快的選擇日期了!
beginDate(newVal, oldVal) {
this.$emit( 'beginDateChange', newVal )
},
endDate(newVal, oldVal) {
this.$emit( 'endDateChange', newVal )
}
}
