uniapp中picker-view 封装时,分,秒选择组件

前言:因为工作中要用到精确到秒的时间组件,uniapp的组件和uview组件都不太合适,所以自己用picker-view 封装一个,写的比较粗糙,有不对的地方请提出来,方便改正,谢谢额。

uniapp中picker-view 封装时,分,秒选择组件_第1张图片

一丶先上代码 html


      //显示时间的地方,样式可以自行修改
		{{ hmsVal }}
		//弹出选择时间的弹框
		
			
				
					取消
					完成
				
				
					
						{{ item }}时
					
					
						{{ item }}分
					
					
						{{ item }}秒
					
				
			
		
	

js

export default {
	props: {
		//父组件传过来的初始值,不是必须传,不传默认值为00:00:00
		hmsval: {
			type: String,
			default() {
				return '00:00:00';
			}
		}
	},
	data() {
		return {
			hours: [],
			minute: [],
			second: [],
			h: '00',
			m: '00',
			s: '00',
			hmsVal: '00:00:00',//页面使用的显示值
			pickerArrIndex: [0, 0, 0]//picker-view 显示默认
		};
	},
	watch: {
	//监听父组件传过来的从新赋值给新的变量显示
		hmsval(newval, oldval) {
			this.hmsVal = newval;
		}
	},
	created() {
		this.hoursFun();
		this.minuteFun();
		this.secondFun();
	},
	methods: {
	// 时
		hoursFun() {
			for (var i = 0; i <= 23; i++) {
				if (i < 10) {
					i = '0' + i;
					this.hours.push(i);
				} else {
					this.hours.push(i);
				}
			}
		},
		// 分
		minuteFun() {
			for (var i = 0; i <= 59; i++) {
				if (i < 10) {
					i = '0' + i;
					this.minute.push(i);
				} else {
					this.minute.push(i);
				}
			}
		},
		// 秒
		secondFun() {
			for (var i = 0; i <= 59; i++) {
				if (i < 10) {
					i = '0' + i;
					this.second.push(i);
				} else {
					this.second.push(i);
				}
			}
		},
		//picker值改变的事件
		bindChange(e) {
			const val = e.detail.value;
			this.h = this.hours[val[0]] ? this.hours[val[0]] : this.h;
			this.m = this.minute[val[1]] ? this.minute[val[1]] : this.m;
			this.s = this.second[val[2]] ? this.second[val[2]] : this.s;
		},
		show() {
			// picker-view 显示默认值
			var hmsArr = this.hmsVal.split(':');
			var hindex = this.hours.findIndex(item => item == hmsArr[0]);
			var mindex = this.minute.findIndex(item => item == hmsArr[1]);
			var sindex = this.second.findIndex(item => item == hmsArr[2]);
			this.pickerArrIndex = [hindex, mindex, sindex];
			this.$refs.popup.open();
		},
		// 关闭popup
		close() {
			this.$refs.popup.close();
		},
		//点击完成
		completeFun() {
			//点击完成赋值
			this.hmsVal = `${this.h}:${this.m}:${this.s}`;
			//新的值传给父组件
			this.$emit('complete',this.hmsVal)
			this.$refs.popup.close();
		}
	}
};

三 css


使用方式

1.父组件

import uniHms from ‘@/components/hms/hms’;//路径改成自己的存放的路径
注册
components: {
uniHms
},
//接收子组件传过来的新值
complete(val){
console.log(val)
}

这个组件拿过去应该可以直接用,显示时间的样式不对可以自行修改,不足的地方请大家提出来多多学习,感谢

你可能感兴趣的:(uni-app,css,前端,vue)