feat(laydate): 新增 formatToDisplay 选项 (#1788)

* feat(laydate): 新增 formatToDisplay 选项

* docs(laydate): 更新 formatToDisplay 文档

* docs(laydate): 优化 `formatToDisplay` 选项的示例代码,以便更直观

* chore: 修改注释词汇,以避免引起不必要的安全性争议

---------

Co-authored-by: 贤心 <3277200+sentsim@users.noreply.github.com>
pull/1804/head
morning-star 7 months ago committed by GitHub
parent f1f0575d15
commit c855d8b19b
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

@ -170,6 +170,29 @@ format: '北京时间 H 点 m 分'
</td> </td>
</tr> </tr>
<tr> <tr>
<td>formatToDisplay <sup>2.9.9+</sup></td>
<td>
仅用于格式化日期显示的格式,不影响日期值
```
formatToDisplay: function (value) {
// value - 日期字符串
var date = new Date(value);
var displayValue = [
value,
date.toLocaleDateString(Intl.LocalesArgument, { weekday: 'long' })
].join(' ')
return displayValue;
};
```
</td>
<td>function</td>
<td>-</td>
</tr>
<tr>
<td> <td>
[value](#options.value) [value](#options.value)

@ -417,6 +417,19 @@
if(options.show || isStatic) that.render(); if(options.show || isStatic) that.render();
isStatic || that.events(); isStatic || that.events();
// 重定义 input 元素的 get set
if(typeof options.formatToDisplay === 'function'){
if(that.isInput(options.elem[0])){
that.formatToDisplay(options.elem[0], options.formatToDisplay);
} else {
var rangeElem = that.rangeElem;
if(rangeElem){
that.formatToDisplay(rangeElem[0][0], options.formatToDisplay);
that.formatToDisplay(rangeElem[1][0], options.formatToDisplay);
}
}
}
//默认赋值 //默认赋值
if(options.value && options.isInitValue){ if(options.value && options.isInitValue){
if(layui.type(options.value) === 'date'){ if(layui.type(options.value) === 'date'){
@ -1931,6 +1944,30 @@
return this.newDate(obj).getTime(); return this.newDate(obj).getTime();
} }
/**
* 格式化输入框显示值
* @param {HTMLInputElement} elem HTML input 元素
* @param {(value: string) => string} displayValueCallback
*/
Class.prototype.formatToDisplay = function (elem, displayValueCallback) {
var that = this;
var props = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype,'value');
Object.defineProperty(
elem,
'value',
lay.extend({}, props, {
get: function () {
return this.getAttribute('lay-date');
},
set: function (value) {
props.set.call(this, displayValueCallback.call(that, value));
this.setAttribute('lay-date', value);
},
})
);
};
//赋值 //赋值
Class.prototype.setValue = function(value){ Class.prototype.setValue = function(value){
var that = this var that = this
@ -1956,7 +1993,8 @@
rangeElem[1].val(value[1] || ''); rangeElem[1].val(value[1] || '');
} else { } else {
if(lay(elem).find('*').length === 0){ if(lay(elem).find('*').length === 0){
lay(elem).html(value); var displayValue = typeof options.formatToDisplay === 'function' ? options.formatToDisplay(value) : value;
lay(elem).html(displayValue);
} }
lay(elem).attr('lay-date', value); lay(elem).attr('lay-date', value);
} }

Loading…
Cancel
Save