持续更新中...
1、发送给朋友,分享到朋友圈功能开启
利用onShareAppMessage和onShareTimeline生命周期函数,在script中与data同级去写
// 发送给朋友
onShareAppMessage() {return {title: '清清前端', // 分享标题path: `/pages/index/index`, // 分享路径,可携带参数imageUrl: ''// 分享图片,可选};},
// 分享到朋友圈onShareTimeline() {return {title: '同心家伴', // 分享标题query: `/pages/userInfo/mineDetil` // 分享参数,注意这里使用query而不是path};},
2、关于小程序中表单校验时,出生年月校验点了确定之后校验文字还是存在的问题
表单中的出生年月input
<u-form-item label="出生年月" borderBottom @click="showDate" prop="birthDate"><u-input disabled v-model="formData.birthDate" disabledColor="#ffffff" placeholder="请选择出生年月"></u-input>
</u-form-item>
点击弹出选择年月日控件
<u-datetime-picker :show="dateShow" v-model="birthDate" mode="date" @confirm="confirmDate" @cancel="cancelDate" :minDate="new Date(1949, 0, 1).getTime()" :maxDate="new Date().getTime()">
</u-datetime-picker>
点击日期控件的确定按钮
confirmDate(e) {const date = new Date(e.value);// 提取年、月、日(月份+1 因为 JS 月份从 0 开始)const year = date.getFullYear();const month = String(date.getMonth() + 1).padStart(2, "0"); // 补零处理(如 1 → "01")const day = String(date.getDate()).padStart(2, "0");// 格式化为 YYYY-MM-DD 并赋值给 formData.birthDatethis.formData.birthDate = `${year}-${month}-${day}`;this.$refs.uForm.validateField('birthDate');this.dateShow = false; // 关闭日期选择器
},
关键语句:this.$refs.uForm.validateField('birthDate'); (单独校验表单其中一个元素时)
onReady() {// 确保表单规则正确设置(小程序兼容)if (this.$refs.uForm?.setRules) {this.$refs.uForm.setRules(this.rules)}
},
3、扫码进入注册页并携带邀请码功能
在微信公众平台 > 开发管理 > 扫普通链接二维码打开小程序,添加对应链接,配置跳转路径。
在扫码跳转小程序成功后,在onLoad函数中可以接收到二维码中的内容
例如,二维码中内容为:https://ceshi.com?inviteCode=123
则在小程序中的query.q的值为:https%3A%2F%2Fceshi.com%2Fa%2F%3Fid%3D123
使用decodeURIComponent解码后可以得到原来的数据,如下所示:
onLoad(options) {// console.log(options);if (options.q) {const optionsUrl = decodeURIComponent(options.q);// console.log(optionsUrl);const inviteCode = this.getQueryString(optionsUrl, 'inviteCode');this.formData.invite = inviteCode; //表单赋值}
},
4、头部导航栏背景铺满顶部
在pages.json中,利用 "navigationStyle": "custom" 属性,来处理导航栏样式,详见 页面配置 | 微信开放文档
以下有单页面自定义导航栏和全局自定义导航栏写法如下:
{"pages": [ {"path": "pages/index/index","style": {"navigationBarTitleText": "uni-app","navigationStyle": "custom" // 单页面自定义导航栏}}],"globalStyle": {"navigationBarTextStyle": "black","navigationBarTitleText": "uni-app","navigationBarBackgroundColor": "#F8F8F8","backgroundColor": "#F8F8F8","navigationStyle": "custom" //全局自定义导航栏},"uniIdRouter": {}
}
4、使用可选链操作符让代码更加简洁
?.
(可选链操作符)
this.$refs.uForm?.setRules?.(this.rules)
等价于传统写法:
if (this.$refs.uForm && this.$refs.uForm.setRules) {this.$refs.uForm.setRules(this.rules);
}
- 如果
this.$refs.uForm
存在, - 并且它有
setRules
这个方法, - 那么就执行
setRules(this.rules)
; - 否则跳过,不执行,也不会报错。