应用场景: 当登录小程序的用户有角色权限限制. 某些板块或功能需要根据所拥有的权限去进行展示或隐藏.
一.先创建自定义组件(权限组件)
// wxml
<view wx-if="{{show}}">
<slot></slot>
</view>
// js
properties: {
// 这里定义了属性,属性值可以在组件使用时指定
// 用于判断该用户是否存在某个权限(调用权限组件的时候传的值)
isHave: {
type: String,
value: ''
},
// 用于控制权限组件是否展示
show: {
type: Boolean,
value: false
}
},
lifetimes: {
// 在组件实例进入页面节点树时执行
attached: function() {
this.getAuthority(this.data.isHave)
},
// 在组件实例被从页面节点树移除时执行
detached: function() {
}
},
methods: {
// 拿到权限数据(来源于登录后的缓存)
getAuthority(isHave){
var authorityData = wx.getStorageSync('你缓存起来的权限')
if(!authorityData) return;
const _isHaveLength_ = authorityData.filter((r)=>r == isHave)
// console.log(_isHaveLength_)
// _isHaveLength_.length 长度大于 0 ,说明存在该权限就 true 展示, 否则不存在就 false 隐藏
this.setData({
show: _isHaveLength_.length > 0 ? true : false
})
}
}
二.在需要设置权限的页面进行调用权限组件
// json(引入自定义组件)
{
"usingComponents": {
"authority": "/components/authority/authority"
}
}
// wxml
<authority isHave="这里传你需要检测的权限">
<view>这是拥有XXX权限才可以展示的板块</view>
</authority>