Authorize.js 2.99 KB
// components/Authorize/Authorize.js
import {
  componentsMixin
} from '../../mixins/index'
Component({
  behaviors: [componentsMixin],
  /**
   * 组件的属性列表
   */
  properties: {
    scopeType: String,
    /**是否自动打开 */
    autoOpen: Boolean,
    show: Boolean,
    title: {
      type: String,
      value: '是否打开授权设置?'
    },
    confirmText: {
      type: String,
      value: '确定'
    },
    cancelText: {
      type: String,
      value: '取消'
    },
    buttonType: String,
    confirmColor: String,
    cancelColor: String,
    isShowCheck: {
      type: Boolean,
      value: true
    },
    init: {
      type: Boolean,
      observer(n) {
        if (n) this.check()
      }
    }
  },
  observers: {
    'show': function (newVal) {
      this.setData({
        openSet: newVal
      })
    }
  },
  /**
   * 组件的初始数据
   */
  data: {

  },
  /**
   * 组件的方法列表
   */
  methods: {
    /**
     * 禁止滑动
     */
    noScroll: wx.$util.noScroll(),
    cancel(e) {
      let {
        confirm
      } = e.currentTarget.dataset
      let {
        buttonType,
        title
      } = this.data
      let _this = this
      if (buttonType == 'getUserInfo' && confirm) {
        wx.getUserProfile({
          desc: title,
          success(res) {
            _this.triggerEvent('success', {
              message: '授权成功',
              data: res
            })
          }
        })
      }
      this.setData({
        openSet: false
      })
      this.triggerEvent('cancel')
    },
    /**检验是否已授权位置 */
    check() {
      const _this = this
      let {
        buttonType,
        scopeType,
        autoOpen
      } = this.properties
      if (buttonType != 'getPhoneNumber') {
        let type = `scope.${scopeType}`
        buttonType = 'openSetting'
        if (type === 'scope.userInfo') buttonType = 'getUserInfo'
        this.setData({
          buttonType
        })
        wx.getSetting({
          success(res) {
            if (!res.authSetting[type]) {
              wx.authorize({
                scope: type,
                success() {
                  _this.triggerEvent('success', {
                    message: '授权成功'
                  })
                },
                fail() {
                  _this.triggerEvent('fail', {
                    message: '未授权'
                  })
                  if (autoOpen) {
                    _this.setData({
                      openSet: true
                    })
                  }
                }
              })
            } else {
              _this.triggerEvent('success', {
                message: '已授权'
              })
            }
          }
        })
      }

    },
    /**授权手机号 */
    getPhoneNumber({
      detail
    }) {
      this.triggerEvent('getphonenumber', detail)
    }
  },
  pageLifetimes: {
    show: function () {
      if (this.data.isShowCheck || this.data.init) this.check()
    },
    hide: function () {}
  }
})