Element-ui踩坑记录 DatePicker 日期选择器

10,930 阅读1分钟

记录自己在使用Element-ui的过程中踩过的坑

报错信息:[Vue warn]: Error in v-on handler: "TypeError: Cannot read property '0' of null"

在使用DatePicker日期选择器选择日期范围的时候,会用到一个属性clearable。这个属性是Boolean变量,用于决定是否显示清除按钮,默认为true

<el-date-picker
   v-model="value"
   type="daterange"
   :clearable="true"
   range-separator="至"
   start-placeholder="开始日期"
   end-placeholder="结束日期">
</el-date-picker>
data(){
  return {
  	value:[]
  }
}

效果:
在选择日期范围之前,value是一个空数组。选择日期后,输出value: 当点击清除按钮后,再次输出value,就会发现这种报错信息:
出现这种情况的原因是: 当点击清除按钮的时候,value会被设置为null
Element-ui中没有内置清除按钮的回调函数。因此要解决这个bug,我使用的方法是在下次调用之前,为value重新赋值,即:

if (!this.value) {
  this.value = []
}