当前位置:   article > 正文

小程序:如何在插件中获取用户手机号_小程序手机号授权组件

小程序手机号授权组件

背景

我们知道,小程序插件中是无法使用 open-type 相关 API 的,官方文档 也有详细说明
在这里插入图片描述
但是如果我们想做一个登录相关的插件,就是要获取用户手机号,该怎么做呢,可以用 引用小程序的自定义组件功能

引用小程序的自定义组件功能介绍

插件中的某一部分(不管是组件还是页面)都可以通过小程序传入一个组件来进行渲染。

实践

小程序端

引入插件

"plugins": {
  "auth-login": {
    "version": "dev",
    "provider": "wxxxxxxxx",
    "genericsImplementation": {
      "auth-login-default": {
        // 将这个组件(get-phone-number-btn)传给插件页(auth-login-default)进行渲染
        "get-phone-number-btn": "components/get-phone-number-btn/index"
      }
    }
  }
},
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

在小程序中按照这个路径 components/get-phone-number-btn/index ,新建一个组件
index.js

Component({
  properties: {
    show: {
      type: Boolean,
      value: false
    },
    phoneStyle: {
      type: String,
      value: ''
    }
  },
  methods: {
    getPhoneNumber (e) {
      console.log('e', e)
      this.triggerEvent('getPhoneNumber', e.detail)
    }
  }
})
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18

index.wxml

<button wx:if="{{ show }}" class="btn-com ok" open-type="getPhoneNumber" bindgetphonenumber="getPhoneNumber" style="{{ phoneStyle }}">微信授权登录</button>
  • 1

index.json

{
  "component": true,
  "usingComponents": {}
}
  • 1
  • 2
  • 3
  • 4

插件端

比如插件端有个页面,叫 auth-login-default,可以在 plugin.json 中查看。
plugin.json

{
  "publicComponents": {},
  "pages": {
    "auth-login-default": "pages/auth-login/index"
  },
  "main": "index.js"
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

"auth-login-default": "pages/auth-login/index" 这个页面中的代码如下:
index.wxml

<text>我是插件原本的代码</text>
// 我是小程序传进来的组件
<get-phone-number-btn show="{{ loginCode && !token && checked }}" bind:getPhoneNumber="getPhoneNumber" phoneStyle="width: 100%;height: 88rpx;line-height: 88rpx;text-align: center;border-radius: 44rpx;border: none;font-size: 32rpx;border: none;outline: none;background: #02C160;color: #fff;" />
  • 1
  • 2
  • 3

index.json

"componentGenerics": {
  "get-phone-number-btn": true
}
  • 1
  • 2
  • 3

index.js

Page({
	async getPhoneNumber (e) {
		// 获取到手机号啦
		console.log(e.detail)
	}
})
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

效果

最终,我们看到这个插件页(auth-login-default)的效果
在这里插入图片描述
点击后也可以调起授权手机号的弹窗啦~

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/菜鸟追梦旅行/article/detail/284573
推荐阅读
相关标签
  

闽ICP备14008679号