Home  >  Article  >  Web Front-end  >  The datepicker plug-in monitors the input box

The datepicker plug-in monitors the input box

php中世界最好的语言
php中世界最好的语言Original
2018-03-23 13:25:391887browse

This time I bring you the datepicker plug-in monitoring input box. What are the precautions for the datepicker plug-in monitoring input box. The following is a practical case, let’s take a look.

1. Background

The third-party datepicker plug-in is used in the Vue project. After selecting the date, Vue cannot detect the change of the datepicker input box

 <label class="fl">日期:</label>
 <p class="input-wrapper fr">
  <input class="daterangepicker" ref="datepicker" v-model="dateRange"/>
  <a href="javascript:;" rel="external nofollow" ></a>
 </p>
export default {
  data() {
    return {
      dateRange: ''
    }
  },
  watch: {
    dateRange(newVal, oldVal) {
      console.log(newVal) // 选择日期后无法监听dateRange的改变
    }
  }
}

2. Analysis

Searching for information found that Vue is actually unable to monitor data changes caused by third-party plug-ins. So the above method won't work. However, Vue provides us with a method that can convert any data into data that can be monitored by Vue, which is: vm.$set.

3. Solution

Take the datepicker I used as an example (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 )
   }
  }

I believe I saw it You have mastered the method in the case of this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

JS method to obtain the top N color values ​​​​of an image

Detailed explanation of graphics and text using the render method

The above is the detailed content of The datepicker plug-in monitors the input box. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn