uniApp项目中使用技巧和细节二

169 阅读4分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路。

一 列表选中功能

1 .vue代码

<view class="chy-query-item-box">
				<view class="chy-query-title">合同状态</view>
				<view class="chy-query-state">
					<view class="chy-select-item" v-for="(item,index) in stateOptions" :key="index"
						@click="selectValue(item.dictValue,index)">
						<view>
							{{item.dictLabel}}

						</view>
						<view v-if="selectShow&&index==selectIndex">
							<u-icon name="checkmark" color="#42B983" size="20"></u-icon>
						</view>
					</view>

				</view>
			</view>
  1. js代码

    变量

    stateOptions: [{
    					dictLabel:'填写中',
    					dictValue:0
    				},{
    					dictLabel:'签署中',
    					dictValue:1
    				},{
    					dictLabel:'已完成',
    					dictValue:2
    				},{
    					dictLabel:'已撤销',
    					dictValue:3
    				},{
    					dictLabel:'已过期',
    					dictValue:4
    				},{
    					dictLabel:'已拒签',
    					dictValue:5
    				}], //状态
        	selectShow: false,//是否展示选中图标
    		selectIndex: 0,//选中项
    

    方法

		selectValue(value, index) {
				this.queryParams.contractState = value;
				if (this.selectIndex == index) {
					this.selectShow = !this.selectShow;
				} else {
					this.selectShow = true;
				}
				this.selectIndex = index;
			},
  1. css代码

    	.chy-query-item-box {
    			margin: 10rpx 0;
    
    			.chy-query-title {
    				font-size: 30rpx;
    				font-weight: bold;
    				padding: 10rpx 0;
    			}
    
    			.chy-query-state {
    				display: flex;
    				justify-content: space-between;
    				align-items: center;
    				flex-wrap: wrap;
    
    				.chy-select-item {
    					width: 30%;
    					border: 2rpx solid #cccccc;
    					border-radius: 20rpx;
    					text-align: center;
    					margin: 20rpx 0;
    					padding: 5rpx 0;
    					display: flex;
    					justify-content: space-around;
    					align-items: center;
    				}
    			}
    		}
    
  2. 效果图 image.png

二 页面返回调用方法

返回页操作js代码

item是选中的对象,signingNameNum是数子变量

	selectItem(item){
				let pages = getCurrentPages()
				// 获取上一页栈
				let prevPage = pages[pages.length - 2]
				// 触发上一页 init函数(可以在括号里携带参数)
				prevPage.$vm.selectUserOk(item,this.signingNameNum);
				uni.navigateBack({
					delta: 1
				})
			}

接受页面js代码

//选中记录
			selectUserOk(item, signingNameNum) {
				let that = this;

				if (item == null || item == undefined || item == '') {
					uni.showToast({
						title: '请选择联系人!',
						icon: 'none'
					});
					return;
				} else {
					that.$nextTick(() => {
						if (signingNameNum == 1) {
							//第一个签约人信息
							that.signingForm.perName1 = item.perName;
							that.signingForm.perMobile1 = item.perMobile;
						} else if (signingNameNum == 2) {
							//第二个签约人信息
							that.signingForm.perName2 = item.perName;
							that.signingForm.perMobile2 = item.perMobile;
						} else if (signingNameNum == 3) {
							//第三个签约人信息
							that.signingForm.perName3 = item.perName;
							that.signingForm.perMobile3 = tem.perMobile;
						} else {
							//企业
							that.signingForm.orgName = item.orgName;
							that.signingForm.orgCode = item.orgCode;
							that.signingForm.perName1 = item.perName;
							that.signingForm.perMobile1 = item.perMobile;
						}
					})
					that.$forceUpdate();//必须加上这么一句代码,否则页面上不展示

				}

			},

效果图

image.png

image.png

### 三 手机号和身份证验证js代码

//保存数据
			saveData() {
				let that = this;
				//保存到数据库数据
				let toDbForm = {
					signCustomerInfoList: [],
					eqbTemplateId: that.signingForm.eqbTemplateId,
					simpleFormFields: [],
				};

				let tempItem1 = {
					perName: that.signingForm.perName1,
					perMobile: that.signingForm.perMobile1,
					orgName: that.signingNum == 0 ? that.signingForm.orgName : "",
					orgCode: that.signingNum == 0 ? that.signingForm.orgCode : "",
					pin: "kh1",
				};
				toDbForm.signCustomerInfoList.push(tempItem1); //第一个人处理

				if (that.signingNum == 2 || that.signingNum == 3) {
					let tempItem2 = {
						perName: that.signingForm.perName2,
						perMobile: that.signingForm.perMobile2,
						orgName: "",
						orgCode: "",
						pin: "kh2",
					};
					toDbForm.signCustomerInfoList.push(tempItem2); //第二个人处理
					if (that.signingNum == 3) {
						let tempItem3 = {
							perName: that.signingForm.perName3,
							perMobile: that.signingForm.perMobile3,
							orgName: "",
							orgCode: "",
							pin: "kh3",
						};
						toDbForm.signCustomerInfoList.push(tempItem3); //第三个人处理
					}
				}
				if (that.signingForm.labelCount && that.signingForm.labelCount != 0) {
					for (let i = 0; i < that.signingForm.labelCount; i++) {//判断表单必填项
						//这里需要增加判断
						let tempValue = that.signingForm[`chyName${i}`][`chyName${i}`];
						let tempLabel = that.signingForm[`chyName${i}`].label;
						let tempId = that.signingForm[`chyName${i}`].id;
						let tempRequired = that.signingForm[`chyName${i}`].required;
						let tempType = that.signingForm[`chyName${i}`].type;
						if (tempRequired) {
							// console.log(that.formCustomer[`chyName${i}`].required,"")
							//console.log("i="+that.formCustomer[`chyName${i}`][`chyName${i}`])

							if (
								tempValue == null ||
								tempValue == undefined ||
								tempValue == ""
							) {

								uni.showToast({
									title: tempLabel + "不能为空!"
								})
								return;
							}

							let patternPhone = /^1[3|4|5|6|7|8|9][0-9]\d{8}$/;
							if (
								tempLabel.includes("手机号") &&
								!patternPhone.test(tempValue)
							) {
								uni.showToast({
									title: tempLabel + "手机号格式不正确!"
								})
								return;
							}
							let pattern =
								/^[1-9]\d{5}[1-9]\d{3}((0[1-9])|(1[0-2]))((0[1-9])|([1-2][0-9])|(3[0-1]))\d{3}(\d|x|X)$/;
							if (
								tempLabel.includes("身份证号") &&
								tempType == 16 &&
								!pattern.test(tempValue)
							) {
								uni.showToast({
									title: tempLabel + "身份证号格式不正确!"
								})

								return;
							}
						}
						if (tempType == 9) {
							tempValue = tempValue.join(",");//数组转字符串
						}
						let tempFields = {
							label: tempLabel,
							id: tempId,
							value: tempValue,
						};
						toDbForm.simpleFormFields.push(tempFields);
						// console.log(i,"i="+i);
					}
				}
				commitDbData(toDbForm).then((response) => { //提交到数据
					uni.showToast({
						title: "保存成功!",
						icon: 'success',
						success(res) {

						},
						fail(err) {

						}
					})

					let userInfolist = [];
					userInfolist = response.data;
					let pages = getCurrentPages()
					// 获取上一页栈
					let prevPage = pages[pages.length - 2]
					//console.log(prevPage,"prevPage")
					// 触发上一页 init函数(可以在括号里携带参数)
					prevPage.$vm.init();
					uni.navigateBack({
						delta: 1
					});
					//this.getList();
					//返回到我合同列表页面
				});
			},

四 下拉刷新方法和回退刷新页面h5和小程序兼容

		onPullDownRefresh() {//下拉刷新
			this.init();
			setTimeout(function() {
				uni.stopPullDownRefresh();
			}, 1000);
		},
           //下面两个是回退刷新 
          onBackPress() {
			console.log('onBackPress')
			let pages = getCurrentPages();
			// 获取上一页栈
			let prevPage = pages[pages.length - 2]
			// 触发上一页 init函数(可以在括号里携带参数)
			prevPage.$vm.init();
		},
		onUnload() {
			console.log('onUnload')
			// #ifdef MP-WEIXIN
			let pages = getCurrentPages()
			// 获取上一页栈
			let prevPage = pages[pages.length - 2]
			// 触发上一页 init函数(可以在括号里携带参数)
			prevPage.$vm.init();
			// #endif
			//uni.$off('sendData')

		},

五 页面多参数传值方法

发送页面代码 如果用URL地址传值需要注意编码和解码,不然是乱码格式。

	handleRelaunch(row) {
				let that = this;
				//先判断模版是否存在存在则打开,不存在则提示
				if (!that.getCheckTemplate(row.templateId)) {
					uni.showToast({
						title: '该模板已经删除,不能重新发起'
					})
					return;
				} else {
					that.signingTitel = row.objectName;
					that.signingForm = {
						eqbTemplateId: row.eqbTemplateId
					};
					that.signingDisabled = true;
					that.signingOpenShow = true
					let url2 = "contractSign"//页面地址
					let params =
						`?signingOpenShow=${that.signingOpenShow}&signingDisabled=${that.signingDisabled}&signingTitel=${encodeURIComponent(that.signingTitel)}&signId=${encodeURIComponent(JSON.stringify(row.signId))}&eqbTemplateId=${encodeURIComponent(JSON.stringify(row.eqbTemplateId))}`; //这个是url地址传值这里没有使用,只是供参考
					uni.navigateTo({
						url: url2,
						success: function(res) {
							res.eventChannel.emit('sendToData', {//这里才是真正传值的地方。
								signingOpenShow: that.signingOpenShow, //控制区域显示
								signingDisabled: that.signingDisabled, //控制是否禁用
								signingTitel: that.signingTitel, //页面标题
								objectId: that.getObjectId(row.objectName), //实体对象ID
								signId: row.signId, //合同id,
								eqbTemplateId: row.eqbTemplateId //e签宝模板的ID
							}); //发送数据给下一个页面

						},
						fail(err) {
							console.log(err);
						}
					});
				}
			},

接受页面代码 这里需要处理兼容行问题

onLoad: function(option) {
			let that = this;

			// #ifndef APP-NVUE
			const eventChannel = this.getOpenerEventChannel();
			// #endif
			// 监听acceptDataFromOpenerPage事件,获取上一页面通过eventChannel传送到当前页面的数据
			eventChannel.once('sendToData', function(res) {
				that.signingTitel = "发起签约——" + res.signingTitel;
				that.signingOpenShow = res.signingOpenShow;
				that.signingDisabled = res.signingDisabled;

				if (res.signId) { //重新发起的数据
					that.signingForm.eqbTemplateId = res.eqbTemplateId;
					let signId = res.signId;
					let eqbTemplateId = res.eqbTemplateId;
					that.getListHistorySignCustomer(signId); //获取签约人信息
					that.getListHistorySignFormData(signId, eqbTemplateId);
					that.getListContractTemplate(res.objectId);
				} else {
					that.getListContractTemplate(res.objectId);
				}
				if (that.signingTitel.includes("企业")) {
					that.signingNum = 0; //0表示企业,1表示一个,2表示两个,3表示三个
				} else if (that.signingTitel.includes("个人")) {
					that.signingNum = 1; //0表示企业,1表示一个,2表示两个,3表示三个
				} else if (that.signingTitel.includes("两人")) {
					that.signingNum = 2; //0表示企业,1表示一个,2表示两个,3表示三个
				} else if (that.signingTitel.includes("三人")) {
					that.signingNum = 3; //0表示企业,1表示一个,2表示两个,3表示三个
				}
			})
		},

六项目经常用到的几个函数方法 includes ,find 和 splice

  1. 判断是否包含代码

    	if (that.signingTitel.includes("企业")) {
    					that.signingNum = 0; //0表示企业,1表示一个,2表示两个,3表示三个
        }
    
  2. 下拉选择获取lable值,find是返回第一个对象,所以可以直接取值

    	stateFormatter(row) {
    				return (
    					(this.stateOptions.find((x) => x.dictValue == row.contractState) &&
    						this.stateOptions.find((x) => x.dictValue == row.contractState)
    						.dictLabel) ||
    					"未知"
    				);
    			},
    
  3. 数组删除项方法 ——非常常用

       //删除标签
        handleClose(tag) {
          //先删除
          this.customerInfo.customerLabelJsonList.splice(
            this.customerInfo.customerLabelJsonList.indexOf(tag),
            1
          );
        }
    

七 列表分组方法 比较常用好用


			toArrData(data) {
				this.followRecordDetail = [];
				let newArr = []
				//通过forEach循环数组
				data.forEach((item, i) => {
					let index = -1
					//然后在跑到这里筛选 根据不同的时间放置不同的数组    some()用来查找数组中是否存在某个值  如果存在 就return true
					let isExists = newArr.some((newItem, j) => {
						if (this.formatTime(item.updateTime) == newItem.updateTime) {
							index = j
							return true
						}
					})
					//代码是先跑这里的if条件判读
					if (!isExists) {
						newArr.push({
							updateTime: this.formatTime(item.updateTime),
							list: [item],//相当于创建动态数组
							newUpdateTime: this.formatTimeYYMMDD(item.updateTime)
						})
					} else {
						newArr[index].list.push(item);
					}
				})
				this.followRecordDetail = newArr;
			},

效果图 是根据日期分组的

image.png

这些都是在项目中使用到的比较常用的方法,记录一下,也方便自己以后能找到。