vue自定义指令配置小程序按钮权限

先创建一个js文件 plugins.js

复制代码
// import {
// 	auth,
// 	authAll
// } from "./tools";
import tools from "./tools.js"
// import Vue from 'vue'

function install(Vue, options) {
	Vue.prototype.$auth = tools.auth;
	Vue.prototype.$authAll = tools.authAll;
	// 注册 v-auth 和 v-auth-all 指令
	Vue.directive('auth', {
		inserted: (el, binding) => {
			if (!auth(binding.value)) {
				el.remove()
			}
		}
	})
	Vue.directive('auth-all', {
		inserted: (el, binding) => {
			if (!authAll(binding.value)) {
				el.remove()
			}
		}
	})
}
export default {
	install
}

再在同级创建一个tools.js文件

复制代码
var roles = [];
roles = uni.getStorageSync("storeRoleRules") ? uni.getStorageSync("storeRoleRules").split(",") : [];
var storeUserType = uni.getStorageSync("storeUserType")
// console.log(roles, '权限');
console.log(storeUserType, '身份');
// 管理员是0  普通员工是1
function hasPermission(permission) {
	return roles.includes(permission)
}

/**
 * 权限数据,如果传入为 array 时,匹配到其中一项则鉴权通过,并显示 slot 内容
 * @param value
 * @returns {*}
 */
function auth(value) {
	let auth;
	if (storeUserType == '0') {
		return true
	}
	if (typeof value === 'string') {
		auth = value !== '' ? hasPermission(value) : true
	} else {
		auth = value.length > 0 ? value.some(item => hasPermission(item)) : true;
	}
	return auth
}

/**
 * 权限数据,如果传入为 array 时,全部匹配则鉴权通过,并显示 slot 内容
 * @param value
 * @returns {*}
 */
function authAll(value) {
	if (storeUserType == '0') {
		return true
	}
	if (value && value.constructor === Array) {
		return value.length > 0 ? value.every(item => hasPermission(item)) : true
	}
	return true;
}

export default {
	auth,
	authAll
}

在main.js中全局引入

复制代码
// 权限
import plugins from '@/utils/plugins.js';
Vue.use(plugins);

最后就可以在页面上使用了

v-auth="['admin-contract-barter-add']" 或 v-auth="admin-contract-barter-add"

看别人写的这两种也行 但是我只有下面这种方法起作用了

复制代码
<view class="go-publish" v-auth="['admin-add']" v-if="$auth(['admin-add'])" @click="goPublish1">
发布商品券
</view>

authAll表示必须有所有的权限才可以,缺一不可

复制代码
<view v-authAll="['admin-add','admin-edit']" v-if="$authAll(['admin-add','admin-edit'])"></view>
相关推荐
mCell19 小时前
GSAP ScrollTrigger 详解
前端·javascript·动效
gnip19 小时前
Node.js 子进程:child_process
前端·javascript
codingandsleeping1 天前
使用orval自动拉取swagger文档并生成ts接口
前端·javascript
白水清风1 天前
微前端学习记录(qiankun、wujie、micro-app)
前端·javascript·前端工程化
用户22152044278001 天前
new、原型和原型链浅析
前端·javascript
阿星做前端1 天前
coze源码解读: space develop 页面
前端·javascript
叫我小窝吧1 天前
Promise 的使用
前端·javascript
用户51681661458411 天前
Vue Router 路由懒加载引发的生产页面白屏问题
vue.js·vue-router
前端康师傅1 天前
JavaScript 作用域
前端·javascript
前端缘梦1 天前
Vue Keep-Alive 组件详解:优化性能与保留组件状态的终极指南
前端·vue.js·面试