uView calendar control (u-calendar) optimization

1 question 

Problems with u-calendar calendar control:

  1. Cannot set default selected value,
  2. When you open the pop-up window and select the start date, and then click the cancel button or mask to close the pop-up window, the selected value in the calendar pop-up window changes (you can see the error in the selected value when you open the calendar pop-up window again).

2 Modify ideas

In response to the above two points, the following modifications have been made to u-calendar with mode="range" to solve the above problems.

Because it is a uView component introduced by npm, the component content cannot be modified in the node_modules directory.

Therefore, you can only copy the u-calendar component to the components directory, rename it to ln-calendar.vue, and modify the component content.

2.1 Set the default selected value

First add the defaultDate attribute in props:

defaultDate: {
	type: Array,
	default: () => []
},

 Second, write a method to set the default value:

//设置默认值,格式['2022-12-1','2023-8-2'],不带0
setDefaultDate(defaultDate) {
    this.setInitData(); //这个方法的内容是,init() 方法中this.changeData();之前所有内容的封装
	if (defaultDate.length == 0) {
		return;
	}
	const startDateArr = defaultDate[0].split('-')
	this.startYear = Number(startDateArr[0])
	this.startMonth = Number(startDateArr[1])
	this.startDay = Number(startDateArr[2])
	this.startDate = this.activeDate = `${this.startYear}-${this.startMonth}-${this.startDay}`
	if (defaultDate.length > 1) {
		const endDateArr = defaultDate[1].split('-')
		this.endYear = Number(endDateArr[0])
		this.endMonth = Number(endDateArr[1])
		this.endDay = Number(endDateArr[2])
		this.endDate = `${this.endYear}-${this.endMonth}-${this.endDay}`
	}
},

 Finally, call the setDefaultDate() method in the init() method. Note that the call must be placed before the changeData() method.

 2.2 Fixed the issue where the selected value in the pop-up window is not restored when unselected.

 First, define two variables in data:

hasFix: false, //识别是否点击了确定按钮
beforeChangeVal: [] //存储原有选中值

 Secondly, in the watch, the listening pop-up window is opened and the click state of the OK button and the original selected value are stored:

value(val) {
	if (val) {
		//保存原有值,点击取消或者蒙版关闭弹窗时,用于复原选中项
		this.hasFix = false
		if (this.startDate && this.endDate) {
			this.beforeChangeVal = [this.startDate, this.endDate]
		} else {
			this.beforeChangeVal = this.startDate ? [this.activeDate] : []
		}
	}
	this.closeFromInner = false;
},

 Then, at the top of the btnFix() method, set the OK button click state to true:

this.hasFix = true

 Finally, in the close() method, fix the problem.

if (!this.hasFix) {
  // 修复点击取消按钮或蒙版关闭弹窗时,日历弹窗的选中值发生改变的问题
  this.setDefaultDate(this.beforeChangeVal);
}

Guess you like

Origin blog.csdn.net/D_lunar/article/details/132166209