permissionBehavior.js 924 Bytes
/**
 * 权限 Behavior:页面/组件引入后自动注入 _perm 到 data
 * 使用:behaviors: [permissionBehavior]
 * 模板中可直接使用:wx:if="{{ _perm.canSelectMultiStore }}"
 */
import { computePermissions } from '~/utils/rolePermission'

export default Behavior({
  data: {
    _perm: {}
  },
  lifetimes: {
    attached() {
      this._updatePerm()
    },
    show() {
      this._updatePerm()
    }
  },
  pageLifetimes: {
    show() {
      this._updatePerm()
    }
  },
  methods: {
    _updatePerm() {
      const userInfo = typeof wx !== 'undefined' && wx.$util ? wx.$util.getUserInfo() : null
      const perm = computePermissions(userInfo)
      if (Object.keys(perm).length && JSON.stringify(this.data._perm) !== JSON.stringify(perm)) {
        this.setData({ _perm: perm })
      }
    },
    /** 便捷方法:检查权限 */
    hasPerm(key) {
      return !!this.data._perm?.[key]
    }
  }
})