溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Vue引用第三方datepicker插件無法監(jiān)聽datepicker輸入框的值怎么辦

發(fā)布時(shí)間:2021-06-29 14:34:30 來源:億速云 閱讀:253 作者:小新 欄目:web開發(fā)

小編給大家分享一下Vue引用第三方datepicker插件無法監(jiān)聽datepicker輸入框的值怎么辦,相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!

一、背景

在Vue項(xiàng)目中使用了第三方的datepicker插件,在選擇日期后vue無法檢測到datepicker輸入框的變化

 <label class="fl">日期:</label>
 <div class="input-wrapper fr">
  <input class="daterangepicker" ref="datepicker" v-model="dateRange"/>
  <a href="javascript:;" rel="external nofollow" ></a>
 </div>
export default {
  data() {
    return {
      dateRange: ''
    }
  },
  watch: {
    dateRange(newVal, oldVal) {
      console.log(newVal) // 選擇日期后無法監(jiān)聽dateRange的改變
    }
  }
}

二、分析

查找資料發(fā)現(xiàn):Vue實(shí)際上無法監(jiān)聽由第三方插件所引起的數(shù)據(jù)變化。因此上面的方法是行不通的。但是,Vue給我們提供的一個(gè)方法,它可以將任意數(shù)據(jù)轉(zhuǎn)化為可以被Vue監(jiān)聽到的數(shù)據(jù),他就是:vm.$set。

三、解決

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

data() {
    return {
      date: '',
      beginDate: '',
      endDate: ''
    }
  },
mounted () {
  $('.daterangepicker').dateRangePicker({
    autoClose: true,
    format: 'YYYY-MM-DD'
  }).bind('datepicker-change', this.setDate) //插件自帶方法,選擇日期后觸發(fā)回調(diào)
 },
methods: {
  setDate() {
    let datepicker = this.$refs.datepicker
    //這一步是關(guān)鍵,具體說明可以參見vue api手冊(cè)
    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: {
  // 這里就可以監(jiān)聽數(shù)據(jù)變化啦,可以愉快的選擇日期了!
   beginDate(newVal, oldVal) {
     this.$emit( 'beginDateChange', newVal )
   },
   endDate(newVal, oldVal) {
     this.$emit( 'endDateChange', newVal )
   }
  }

以上是“Vue引用第三方datepicker插件無法監(jiān)聽datepicker輸入框的值怎么辦”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對(duì)大家有所幫助,如果還想學(xué)習(xí)更多知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI