首页 > 语言 > JavaScript > 正文

Vue引用第三方datepicker插件无法监听datepicker输入框的值的解决

2024-05-06 15:22:19
字体:
来源:转载
供稿:网友

一、背景

在Vue项目中使用了第三方的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) // 选择日期后无法监听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 )   }  }

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持错新站长站。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选