前言:微信小程序发送模板信息有两个前提,要么触发一次表单提交,要么触发一次支付。如果需要给用户主动推送模板信息,那么就需要拿到足够多的formId(支付不实现),下面介绍如何才能获取足够多的formId。
PS:使用该方法的时候需要符合微信运行规则。
思路:我们封装一个组件,组件内部是一个form标签和一个提交按钮,form表单支持返回formId,然后该组件接收外部标签(也就是slot)和一个回调函数,当点击该组件的时候,触发表单提交并向上冒泡(外部组件的内部时间会无效,只能通过回调方法来触发)。
第一步:创建catchform捕获组件

<form class="catchForm" report-submit bindsubmit="catchSubmit" >
<button form-type="submit" class="catchBtn">
<slot ></slot >
</button>
</form>
第二步:优化CSS
因为button按钮的样式权重高,行号和其他属性均有自己的定义,会严重影响内部组件的ui,所以要对button的样式就行重置,主要思路是继承父级的样式。

form.catchForm button.catchBtn {
border: none;
text-align: inherit;
padding: 0;
margin: 0;
line-height: inherit;
background: transparent;
color: inherit;
border-radius: 0;
font-size: inherit;
}
form.catchForm button.catchBtn::after {
border: none;
}
第三步:处理组件form提交
提交的时候会触发catchSubmit函数,catchSubmit函数内部同步表单信息和触发回调,代码如下:

Component({
/**
* 组件的属性列表
*/
properties: {
},
/**
* 组件的初始数据
*/
data: {
upload: {
type: Boolean,
value: true
}
},
/**
* 组件的方法列表
*/
methods: {
//点击即触发获取formId
catchSubmit: function (e) {
if (this.data.upload) {
try {
Request.post("/api/uploadFormId", {
formId: e.detail.formId,
touser: getApp().globalData.userInfo.openid,
time: new Date()
});
} catch (err) {
//todo
}
}
//触发回调
this.callback(e);
},
/**
* 捕获点击回调
*/
callback: function (e) {
try {
this.triggerEvent("callback", e);
} catch (err) {
//todo
}
}
}
})
第四步:使用catchform捕获组件

bind:callback="toDetail",指触发表单提交后的回调函数
data-record="{{item}}" , 是自定义参数
后续再根据formId和openId就可以发送模板信息了
网友评论