缘起🧐
开始的开始,简单粗暴。在微信小程序里,一行wx.getUserInfo即可弹窗用户授权登陆。大部分小程序图省事,直接在打开小程序的时候就调这个方法。所以那时候一个印象就是随便打开一个小程序,进去就是弹窗让我登陆,想拿我的微信信息,给人一种不安全的感觉。
当时的代码长这样:
1 2 3 4 5 6 7
| <script> wx.getUserInfo({ success(res) { } }) </script>
|
如果要与业务结合起来,通常会是这样(以下代码示例均使用wepy框架):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| <template> <view @tap="clickA">需要登陆操作A</view> <view @tap="clickB">需要登陆操作B</view> </template> <script> { methods = { clickA () { await getUserInfo() } clickB () { await getUserInfo() } } } </script>
|
变数😩
为了防止滥用,微信后来决定调整这个交互,改变了授权登陆流程。于是就发布了一个公告,很突然的,就是直接调wx.getUserInfo不再弹窗询问用户是否授权。而是需要使用原生button组件,用户实际操作点击了屏幕才能触发。
此时的代码变成了这个熊样:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| <template> <button open-type="getUserInfo" bindgetuserinfo="bindGetUserInfo"> 点击授权登陆 </button> </template> <script> { methods = { bindGetUserInfo (e) { } } } </script>
|
看上去问题不大,其实已经原地爆炸。现在如果和业务结合起来就会有很多赘余代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| <template> <view> <button class="auth-btn" open-type="getUserInfo" bindgetuserinfo="clickA"></button> 需要登陆操作A </view> <view> <button class="auth-btn" open-type="getUserInfo" bindgetuserinfo="clickB"></button> 需要登陆操作B </view> </template> <script> { methods = { clickA (e) { if (e.detail.errMsg === 'getUserInfo:ok') { } } clickB (e) { if (e.detail.errMsg === 'getUserInfo:ok') { } } } } </script> <style lang="less"> .auth-btn { // 使其cover在父容器上并透明 } </style>
|
之前接手过一个遗留项目,里面密密麻麻充斥着这种代码,我看5分钟吐了3次🤮。DRY!DRY!DRY!有代码洁癖加重度强迫症的我完全不能忍。
归途😎
作为一个有追求的追风少年,思虑良久,得想个辙🤔,不然之后的开发生涯就充斥着难受。wepy是一个组件化的小程序框架,可以像写vue组件一样去写小程序的自定义组件。于是就有了一个很自然的想法。把登陆按钮封装起来,使其足够方便。
最后的最后,组件化后的代码长这样🚀:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| <template> <view> <LoginButton1 @tap.user="clickA"></LoginButton1> 需要登陆操作A </view> <view> <LoginButton2 @tap.user="clickB"></LoginButton2> 需要登陆操作B </view> </template> <script> import LoginButton from '@/components/LoginButton' { components = { LoginButton1: LoginButton, LoginButton2: LoginButton, } methods = { clickA () { } clickB () { } } </script>
|
{ LoginButton1: LoginButton, LoginButton2: LoginButton }
这个诡异的写法主要是因为wepy的组件是静态组件(其实就是编译时代码复制),导致每实例化一个都要分配一个id😐。据说wepy即将发布2.0版本,会解决这个问题,甚是期待。
这可能不是最优方案,但确实方便了许多。