報錯信息:[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="datetimerange" :clearable="true" range-separator="至" start-placeholder="開始日期" end-placeholder="結束日期" value-format="yyyy-MM-dd HH:mm:ss"> </el-date-picker>
data(){ return { value:[] } }
效果:
在選擇日期范圍之前,value
是一個空數組。選擇日期后,輸出value
:
當點擊清除按鈕后,再次輸出value
,就會發現這種報錯信息:
出現這種情況的原因是: 當點擊清除按鈕的時候,value
會被設置為null
。
Element-ui中沒有內置清除按鈕的回調函數。因此要解決這個bug
,我使用的方法是在下次調用之前,為value
重新賦值,即:
if (!this.value) { this.value = [] }
或者在取值的時候判斷一下,即:
this.searchForm.startTime = this.value ? this.value[0] || '' : ''; this.searchForm.endTime = this.value ? this.value[1] || '' : '';