uniapp微信小程序使用uview-plus实现日期选择封装

uniapp yekong 233℃

uniapp 微信小程序开发过程中,需要实现日期选择,但是当前页面可能会出现多个日期选择,如果每个日期选择都要写一套代码会让代码臃肿不便于维护。

uniapp微信小程序使用uview-plus实现日期选择封装

这里我们对这个日期选择进行封装

封装一个getdate的组件

<template>
	<div>
		<div class="slot" @click="getShow">
			<slot></slot>
		</div>
		<!-- 时间选择器 -->
		<up-datetime-picker ref="datetimePickerRef" title='时间选择' :formatter='formatter' :show="show"
			:value="value" @confirm="handleConfirm" cancelColor="rgba(51, 51, 51, 1)" confirmText='确定'
			confirmColor='rgba(71, 133, 255, 1)' @cancel="handleCancel" mode="date"></up-datetime-picker>
	</div>
</template>

<script>
	export default {
		props: {
			value: String  // 接收从父组件传入的时间值
		},
		data() {
			return {
				show: false,
			};
		},
		methods: {
			formatter(type, value) {
				if (type === 'year') {
					return `${value}年`;
				}
				if (type === 'month') {
					return `${value}月`;
				}
				if (type === 'day') {
					return `${value}日`;
				}
				return value;
			},
			handleConfirm(value) {
				this.show = false;
				this.$emit('update:value', value.value);  // 触发事件,传回选中的日期
				console.log('日期更新为:', value);
			},
			handleCancel() {
				this.show = false;
				console.log('日期选择已取消');
			},
			getShow() {
				this.show = true;
			},
		}
	}
</script>

父组件使用

使用插槽的方式将对应的div插入到组件中,然后点击触发子组件的选择日期,界面只需要一个更新这个日期就可以了。

<getdate v-model:value="data.startTime">
	<div class="item">
		<div class="itemTitle">就诊时间</div>
		<div class="itemBody">
			<input type="text" :disabled="true" :value="formattedDate?formattedDate:'请选择'">
			<image class="iconRight" src="../../../static/iconRight.png"></image>
		</div>
	</div>
</getdate>
喜欢 (0)