UViewUI组件时间选择器修改,可单独选 年,选择 年-月 ,选择年-月-日-时

博客介绍了如何修改UView-UI的日期选择组件,以实现选择年和年月日时的功能。通过设置不同的`mode`值,如`year`和`date-hour`,可以分别实现年份选择和年月日时的组合选择。代码示例展示了组件模板、监听属性变化以及方法实现,包括初始化、事件处理和列更新等关键步骤。

以下功能更都是需要走修改UView-UI的日期选择组件的代码的,先上效果图

选择 年

mode 填写:year
在这里插入图片描述

选择 年-月-日-时

mode 填写:date-hour
在这里插入图片描述
代码:

<template>
	<u-picker
		ref="picker"
		:show="show"
		:closeOnClickOverlay="closeOnClickOverlay"
		:columns="columns"
		:title="title"
		:itemHeight="itemHeight"
		:showToolbar="showToolbar"
		:visibleItemCount="visibleItemCount"
		:defaultIndex="innerDefaultIndex"
		:cancelText="cancelText"
		:confirmText="confirmText"
		:cancelColor="cancelColor"
		:confirmColor="confirmColor"
		@close="close"
		@cancel="cancel"
		@confirm="confirm"
		@change="change"
	>
	</u-picker>
</template>

<script>
	function times(n, iteratee) {
	    let index = -1
	    const result = Array(n < 0 ? 0 : n)
	    while (++index < n) {
	        result[index] = iteratee(index)
	    }
	    return result
	}
	import props from './props.js';
	import dayjs from '../../libs/util/dayjs.js';
	/**
	 * DatetimePicker 时间日期选择器
	 * @description 此选择器用于时间日期
	 * @tutorial https://www.uviewui.com/components/datetimePicker.html
	 * @property {Boolean}			show				用于控制选择器的弹出与收起 ( 默认 false )
	 * @property {Boolean}			showToolbar			是否显示顶部的操作栏  ( 默认 true )
	 * @property {String | Number}	value				绑定值
	 * @property {String}			title				顶部标题
	 * @property {String}			mode				展示格式 mode=date为日期选择,mode=time为时间选择,mode=year-month为年月选择,mode=datetime为日期时间选择  ( 默认 ‘datetime ),自定义增加 year 选择年, year-month 选择年月, date-hour选择年月日时
	 * @property {Number}			maxDate				可选的最大时间  默认值为后10年
	 * @property {Number}			minDate				可选的最小时间  默认值为前10年
	 * @property {Number}			minHour				可选的最小小时,仅mode=time有效   ( 默认 0 )
	 * @property {Number}			maxHour				可选的最大小时,仅mode=time有效	  ( 默认 23 )
	 * @property {Number}			minMinute			可选的最小分钟,仅mode=time有效	  ( 默认 0 )
	 * @property {Number}			maxMinute			可选的最大分钟,仅mode=time有效   ( 默认 59 )
	 * @property {Function}			filter				选项过滤函数
	 * @property {Function}			formatter			选项格式化函数
	 * @property {Boolean}			loading				是否显示加载中状态   ( 默认 false )
	 * @property {String | Number}	itemHeight			各列中,单个选项的高度   ( 默认 44 )
	 * @property {String}			cancelText			取消按钮的文字  ( 默认 '取消' )
	 * @property {String}			confirmText			确认按钮的文字  ( 默认 '确认' )
	 * @property {String}			cancelColor			取消按钮的颜色  ( 默认 '#909193' )
	 * @property {String}			confirmColor		确认按钮的颜色  ( 默认 '#3c9cff' )
	 * @property {String | Number}	visibleItemCount	每列中可见选项的数量  ( 默认 5 )
	 * @property {Boolean}			closeOnClickOverlay	是否允许点击遮罩关闭选择器  ( 默认 false )
	 * @property {Array}			defaultIndex		各列的默认索引
	 * @event {Function} close 关闭选择器时触发
	 * @event {Function} confirm 点击确定按钮,返回当前选择的值
	 * @event {Function} change 当选择值变化时触发
	 * @event {Function} cancel 点击取消按钮
	 * @example  <u-datetime-picker :show="show" :value="value1"  mode="datetime" ></u-datetime-picker>
	 */
	export default {
		name: 'datetime-picker',
		mixins: [uni.$u.mpMixin, uni.$u.mixin, props],
		data() {
			return {
				columns: [],
				innerDefaultIndex: [],
				innerFormatter: (type, value) => value
			}
		},
		watch: {
			show(newValue, oldValue) {
				if (newValue) {
					this.updateColumnValue(this.innerValue)
				}
			},
			propsChange() {
				this.init()
			}
		},
		computed: {
			// 如果以下这些变量发生了变化,意味着需要重新初始化各列的值
			propsChange() {
				return [this.value,this.mode, this.maxDate, this.minDate, this.minHour, this.maxHour, this.minMinute, this.maxMinute, this.filter, ]
			}
		},
		mounted() {
			this.init()
		},
		methods: {
			init() {
				this.innerValue = this.correctValue(this.value)
				this.updateColumnValue(this.innerValue)
			},
			// 在微信小程序中,不支持将函数当做props参数,故只能通过ref形式调用
			setFormatter(e) {
				this.innerFormatter = e
			},
			// 关闭选择器
			close() {
				if (this.closeOnClickOverlay) {
					this.$emit('close')
				}
			},
			// 点击工具栏的取消按钮
			cancel() {
				this.$emit('cancel')
			},
			// 点击工具栏的确定按钮
			confirm() {
				this.$emit('confirm', {
					value: this.innerValue,
					mode: this.mode
				})
				this.$emit('input', this.innerValue)
			},
			//用正则截取输出值,当出现多组数字时,抛出错误
			intercept(e,type){
				let judge = e.match(/\d+/g)
				//判断是否掺杂数字
				if(judge.length>1){
					uni.$u.error("请勿在过滤或格式化函数时添加数字")
					return 0
				}else if(type&&judge[0].length==4){//判断是否是年份
					return judge[0]
				}else if(judge[0].length>2){
					uni.$u.error("请勿在过滤或格式化函数时添加数字")
					return 0
				}else{
					return judge[0]
				}
			},
			// 列发生变化时触发
			change(e) {
				const { indexs, values } = e
				let selectValue = ''
				if(this.mode === 'time') {
					// 根据value各列索引,从各列数组中,取出当前时间的选中值
					selectValue = `${this.intercept(values[0][indexs[0]])}:${this.intercept(values[1][indexs[1]])}`
				} else {
					
					// 将选择的值转为数值,比如'03'转为数值的3,'2019'转为数值的2019
					const year = parseInt(this.intercept(values[0][indexs[0]],'year'))
					let month = 1
					if (this.mode !== 'year') {
						month = parseInt(this.intercept(values[1][indexs[1]]))
					}
					let date = parseInt(values[2] ? this.intercept(values[2][indexs[2]]) : 1)
					let hour = 0, minute = 0
					// 此月份的最大天数
					const maxDate = dayjs(`${year}-${month}`).daysInMonth()
					// year-month模式下,date不会出现在列中,设置为1,为了符合后边需要减1的需求
					if (this.mode === 'year') {
					    date = 1
					}
					if (this.mode === 'year-month') {
					    date = 1
					}
					// 不允许超过maxDate值
					date = Math.min(maxDate, date)
					if (this.mode === 'datetime') {
					    hour = parseInt(this.intercept(values[3][indexs[3]]))
					    minute = parseInt(this.intercept(values[4][indexs[4]]))
					}
				
					if (this.mode === 'date-hour') {
					    hour = parseInt(this.intercept(values[3][indexs[3]]))
					}
					// 转为时间模式
					selectValue = Number(new Date(year, month - 1, date, hour, minute))
				}
				// 取出准确的合法值,防止超越边界的情况
				selectValue = this.correctValue(selectValue)
				this.innerValue = selectValue
				this.updateColumnValue(selectValue)
				// 发出change时间,value为当前选中的时间戳
				this.$emit('change', {
					value: selectValue,
					// #ifndef MP-WEIXIN
					// 微信小程序不能传递this实例,会因为循环引用而报错
					picker: this.$refs.picker,
					// #endif
					mode: this.mode
				})
			},
			// 更新各列的值,进行补0、格式化等操作
			updateColumnValue(value) {
				this.innerValue = value
				this.updateColumns()
				this.updateIndexs(value)
			},
			// 更新索引
			updateIndexs(value) {
				let values = []
				const formatter = this.formatter || this.innerFormatter
				const padZero = uni.$u.padZero
				if (this.mode === 'time') {
					// 将time模式的时间用:分隔成数组
				    const timeArr = value.split(':')
					// 使用formatter格式化方法进行管道处理
				    values = [formatter('hour', timeArr[0]), formatter('minute', timeArr[1])]
				} else {
				    const date = new Date(value)
				    values = [
				        formatter('year', `${dayjs(value).year()}`),
						// 月份补0
				        formatter('month', padZero(dayjs(value).month() + 1))
				    ]
					if (this.mode === 'year') {
						// 数组的push方法,可以写入多个参数
					    values.push(formatter('day', padZero(dayjs(value).date())))
					}
				    if (this.mode === 'date') {
						// date模式,需要添加天列
				        values.push(formatter('day', padZero(dayjs(value).date())))
				    }
					if (this.mode === 'date-hour') {
						// 数组的push方法,可以写入多个参数
					    values.push(formatter('day', padZero(dayjs(value).date())), formatter('hour', padZero(dayjs(value).hour())))
					}
					 if (this.mode === 'datetime') {
						// 数组的push方法,可以写入多个参数
				        values.push(formatter('day', padZero(dayjs(value).date())), formatter('hour', padZero(dayjs(value).hour())), formatter('minute', padZero(dayjs(value).minute())))
				    }
				}

				// 根据当前各列的所有值,从各列默认值中找到默认值在各列中的索引
				const indexs = this.columns.map((column, index) => {
					// 通过取大值,可以保证不会出现找不到索引的-1情况
					return Math.max(0, column.findIndex(item => item === values[index]))
				})
				this.innerDefaultIndex = indexs
			},
			// 更新各列的值
			updateColumns() {
			    const formatter = this.formatter || this.innerFormatter
				// 获取各列的值,并且map后,对各列的具体值进行补0操作
			    const results = this.getOriginColumns().map((column) => column.values.map((value) => formatter(column.type, value)))
				this.columns = results
			},
			getOriginColumns() {
			    // 生成各列的值
			    const results = this.getRanges().map(({ type, range }) => {
			        let values = times(range[1] - range[0] + 1, (index) => {
			            let value = range[0] + index
			            value = type === 'year' ? `${value}` : uni.$u.padZero(value)
			            return value
			        })
					// 进行过滤
			        if (this.filter) {
			            values = this.filter(type, values)
			        }
			        return { type, values }
			    })
			    return results
			},
			// 通过最大值和最小值生成数组
			generateArray(start, end) {
				return Array.from(new Array(end + 1).keys()).slice(start)
			},
			// 得出合法的时间
			correctValue(value) {
				const isDateMode = this.mode !== 'time'
				if (isDateMode && !uni.$u.test.date(value)) {
					// 如果是日期类型,但是又没有设置合法的当前时间的话,使用最小时间为当前时间
					value = this.minDate
				} else if (!isDateMode && !value) {
					// 如果是时间类型,而又没有默认值的话,就用最小时间
					value = `${uni.$u.padZero(this.minHour)}:${uni.$u.padZero(this.minMinute)}`
				}
				// 时间类型
				if (!isDateMode) {
					if (String(value).indexOf(':') === -1) return uni.$u.error('时间错误,请传递如12:24的格式')
					let [hour, minute] = value.split(':')
					// 对时间补零,同时控制在最小值和最大值之间
					hour = uni.$u.padZero(uni.$u.range(this.minHour, this.maxHour, Number(hour)))
					minute = uni.$u.padZero(uni.$u.range(this.minMinute, this.maxMinute, Number(minute)))
					return `${ hour }:${ minute }`
				} else {
					// 如果是日期格式,控制在最小日期和最大日期之间
					value = dayjs(value).isBefore(dayjs(this.minDate)) ? this.minDate : value
					value = dayjs(value).isAfter(dayjs(this.maxDate)) ? this.maxDate : value
					return value
				}
			},
			// 获取每列的最大和最小值
			getRanges() {
			    if (this.mode === 'time') {
			        return [
			            {
			                type: 'hour',
			                range: [this.minHour, this.maxHour],
			            },
			            {
			                type: 'minute',
			                range: [this.minMinute, this.maxMinute],
			            },
			        ];
			    }
			    const { maxYear, maxDate, maxMonth, maxHour, maxMinute, } = this.getBoundary('max', this.innerValue);
			    const { minYear, minDate, minMonth, minHour, minMinute, } = this.getBoundary('min', this.innerValue);
			    const result = [
			        {
			            type: 'year',
			            range: [minYear, maxYear],
			        },
			        {
			            type: 'month',
			            range: [minMonth, maxMonth],
			        },
			        {
			            type: 'day',
			            range: [minDate, maxDate],
			        },
			        {
			            type: 'hour',
			            range: [minHour, maxHour],
			        },
			        {
			            type: 'minute',
			            range: [minMinute, maxMinute],
			        },
			    ];
				if (this.mode === 'year') // 让其只显示 年
					result.splice(1, 4);
			    if (this.mode === 'date')
			        result.splice(3, 2);
				if (this.mode === 'date-hour') // 让其只显示 年月日时
					result.splice(4, 1);
				  if (this.mode === 'year-month')
			        result.splice(2, 3);
			    return result;
			},
			// 根据minDate、maxDate、minHour、maxHour等边界值,判断各列的开始和结束边界值
			getBoundary(type, innerValue) {
			    const value = new Date(innerValue)
			    const boundary = new Date(this[`${type}Date`])
			    const year = dayjs(boundary).year()
			    let month = 1
			    let date = 1
			    let hour = 0
			    let minute = 0
			    if (type === 'max') {
			        month = 12
					// 月份的天数
			        date = dayjs(value).daysInMonth()
			        hour = 23
			        minute = 59
			    }
				// 获取边界值,逻辑是:当年达到了边界值(最大或最小年),就检查月允许的最大和最小值,以此类推
			    if (dayjs(value).year() === year) {
			        month = dayjs(boundary).month() + 1
			        if (dayjs(value).month() + 1 === month) {
			            date = dayjs(boundary).date()
			            if (dayjs(value).date() === date) {
			                hour = dayjs(boundary).hour()
			                if (dayjs(value).hour() === hour) {
			                    minute = dayjs(boundary).minute()
			                }
			            }
			        }
			    }
			    return {
			        [`${type}Year`]: year,
			        [`${type}Month`]: month,
			        [`${type}Date`]: date,
			        [`${type}Hour`]: hour,
			        [`${type}Minute`]: minute
			    }
			},
		},
	}
</script>

<style lang="scss" scoped>
	@import '../../libs/css/components.scss';
</style>

下载查看源代码:
UView 时间选择器源代码修改,增加可选‘年’、‘年-月-日-时’的功能

<think>我们正在使用uni-appuViewUI组件库,特别是<u-upload>组件。用户想知道如何监听文件选择前的事件。根据uView文档,<u-upload>组件提供了多个事件,包括选择文件之前的事件。具体来说,我们可以使用`before-choose`事件。但是,请注意,在uView的官方文档中,这个事件可能被命名为`before-choose`或者类似的名字。在uView2.0中,我们可以使用`before-upload`事件,但它是在上传之前触发,而选择文件之前的事件应该是`before-choose`。然而,查阅uView2.0的文档(https://www.uviewui.com/components/upload.html),我们发现它提供了以下事件: -`on-list-change`:文件列表发生变化触发- `on-uploaded`:所有文件上传完成后触发- `on-choose-complete`:选择文件后触发- `on-remove`:移除文件触发但并没有直接提供选择文件之前的事件。但是,我们注意到有一个名为`before-upload`的事件,它在上传之前触发,但这不是选择文件之前,而是选择文件之后,上传之前。那么如何监听选择文件之前的事件呢?实际上,在uView组件中,有一个`before-choose`属性(注意:不是事件,而是属性)可以用于在文件选择前进行一些校验,并决定是否继续选择。这个属性是一个函数,返回一个布尔值(或者Promise返回布尔值),如果返回false,则不会弹出文件选择框。因此,我们可以这样使用:```html<u-upload:before-choose="beforeChoose"></u-upload>```在methods中定义beforeChoose方法: ```jsmethods:{beforeChoose() {//这里可以执行一些操作,比如检查用户是否登录等console.log('选择文件之前');//返回true表示继续选择,返回false则取消选择return true;} }```但是,请注意,这个`before-choose`属性在uView文档中实际上被描述为:选择图片前的回调函数,参数为index(从哪个图片开始选择)。在uView2.0中,它确实是一个函数,用于在文件选择前进行拦截。所以,用户想要监听选择文件之前的事件,实际上就是使用这个`before-choose`属性(在组件中作为属性传递,但它的值是一个函数,会在选择前被调用)。另外,如果用户使用的是uView1.x版本,可能事件名称有所不同,但当前uView2.0是比较常用的版本,我们以2.0为准。因此,回答用户:可以通过设置`before-choose`属性为一个函数,在这个函数里执行选择文件前的操作,并返回true或false来决定是否继续选择。但是,请注意:这个事件并不是以事件监听的形式(如`@before-choose`)来使用的,而是作为组件的一个属性。所以,在模板中我们使用`:before-choose="beforeChoose"`。如果用户需要的是在选择文件之前弹出一个确认框,那么可以这样写:```jsbeforeChoose(){//返回一个Promise,用于异步操作,比如弹出确认框return newPromise((resolve,reject)=> {uni.showModal({title:'提示',content:'确定要选择文件吗?',success: (res)=> {if(res.confirm) {resolve(true);//继续选择} else{resolve(false); //取消选择}}});});} ```注意:在uView2.0中,`before-choose`可以返回一个Promise,因此我们可以执行异步操作。总结:使用`before-choose`属性(注意是属性,不是事件)来监听选择文件前的动作,并控制是否继续选择。另外,如果用户使用的是uni-app的原生上传组件,那么可能没有这个事件。但这里用户明确使用了uView的u-upload组件,所以我们按照uView的用法来回答。根据引用[3]中提到的“利用computed监听用户操作”,但这里我们并不需要computed,因为这是一个方法调用。因此,回答如下:</think>在 uni-app 中使用 uView UI 的 `<u-upload>` 组件监听文件选择前的事件,可以通过 `before-choose` 属性实现。以下是具体实现方法: ### 解决方案 1. **使用 `before-choose` 属性** uView 的 `<u-upload>` 组件提供了 `before-choose` 属性,该属性接受一个函数,会在用户点击选择文件按钮**前**触发。通过返回 `true`/`false` 或 `Promise` 可控制是否继续执行文件选择操作。 2. **代码实现**: ```vue <template> <u-upload :before-choose="beforeChoose" :action="uploadUrl" @on-success="uploadSuccess" ></u-upload> </template> <script> export default { methods: { // 文件选择前的回调函数 beforeChoose() { console.log("即将打开文件选择"); // 示例1:同步拦截(返回布尔值) if (!this.userHasPermission) { uni.showToast({ title: '无操作权限', icon: 'error' }); return false; // 阻止文件选择 } return true; // 允许文件选择 // 示例2:异步拦截(返回Promise) return new Promise((resolve) => { uni.showModal({ title: '确认', content: '是否选择文件?', success: (res) => { resolve(res.confirm); // 用户确认则继续选择 } }); }); }, uploadSuccess(res) { console.log("上传成功", res); } }, data() { return { uploadUrl: "https://your-api.com/upload", // 替换为实际接口 userHasPermission: true // 权限状态示例 }; } }; </script> ``` ### 关键点说明 1. **`before-choose` 返回值**: - **`true`**:允许打开文件选择 - **`false`**:阻止文件选择操作 - **`Promise`**:异步控制(如弹窗确认),需返回最终布尔值 2. **典型应用场景**: - 权限检查(如用户是否登录) - 操作确认(弹窗提示) - 业务条件校验(如剩余上传次数) - 预处理操作(如清理缓存) 3. **注意事项**: - 该属性**仅拦截选择操作**,不影响已文件的上传 - 如需监听文件选择**后**的事件,使用 `@on-choose-complete` - 上传逻辑需在 `action` 属性配置接口地址,并通过 `@on-success` 处理结果 ### 相关扩展问题 1. `before-choose` 和 `before-upload` 有何区别? `before-choose` 在**选择文件前**触发(未获取文件),`before-upload` 在**上传前**触发(已获取文件,可修改文件数据)。 2. 如何限制文件类型和大小? 使用 `accept` 属性限制类型(如 `accept="image/*"`),通过 `max-size` 属性限制大小(单位字节): ```vue <u-upload accept="image/png,image/jpeg" :max-size="5 * 1024 * 1024" // 5MB ></u-upload> ``` 3. 如何获取选择的文件信息? 通过 `@on-choose-complete` 事件获取文件列表: ```vue <u-upload @on-choose-complete="handleFilesChosen"></u-upload> ``` ```js methods: { handleFilesChosen(files) { console.log("已文件", files); } } ``` > 引用说明:uView 的 `before-choose` 机制类似于拦截设计模式,通过前置回调实现流程控制[^3],而文件上传逻辑需遵循 multipart/form-data 规范与服务交互[^1]。组件结构参考 uni-app 标准项目规范[^2]。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值