Vue引用第三方datepicker插件沒法監聽datepicker輸入框的值

1、背景

在Vue項目中使用了第三方的datepicker插件,在選擇日期後vue沒法檢測到datepicker輸入框的變化javascript

<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的改變
        }
    }
}

2、分析

查找資料發現:Vue實際上沒法監聽由第三方插件所引發的數據變化。所以上面的方法是行不通的。可是,Vue給咱們提供的一個方法,它能夠將任意數據轉化爲能夠被Vue監聽到的數據,他就是:vm.$set。html

3、解決

以我用到的datepicker爲例(jquery-daterangepicker)vue

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 )
      }
    }
相關文章
相關標籤/搜索