import Vue from 'vue'; import { Message } from 'element-ui'; import { check } from '@/utils/auth'; // 限制按钮点击事件,执行原有操作之前判断用户是否有权限 Vue.directive('auth', { // 插入dom 时做的事情 inserted: (el, bind) => { const { modifiers = [], value: callback } = bind; const authority = el.getAttribute('authority') || []; const msg = el.getAttribute('msg') || '您无权进行此操作'; el.addEventListener('click', () => { // 需要登录 if (modifiers['login']) { return Vue.prototype.$login(); } // 需要访问权限 if (authority.length !== 0 && !check(authority)) { // Message.warning(msg); Vue.prototype.$Alert(msg, '好的', '#f19e38'); return; } callback(); }); }, }); Vue.directive('copy', { inserted: (el) => { el.style.cursor = 'pointer'; }, bind(el, { modifiers = [], value }) { el.$value = value; el.handler = (e) => { if (modifiers['stop']) { e.stopPropagation(); e.cancelBubble = true; } if (!el.$value) { Message.warning('无复制内容'); return; } // 动态创建 textarea 标签 const textarea = document.createElement('textarea'); // 将该 textarea 设为 readonly 防止 iOS 下自动唤起键盘,同时隐藏 textarea textarea.readOnly = 'readonly'; textarea.display = 'none'; // 将要 copy 的值赋给 textarea 标签的 value 属性 textarea.value = el.$value; // 将 textarea 插入到 body 中 document.body.appendChild(textarea); // 选中值并复制 textarea.select(); const result = document.execCommand('Copy'); if (result) { const msg = el.getAttribute('msg') || '复制成功'; Message.success(msg); } document.body.removeChild(textarea); }; // 绑定点击事件,就是所谓的一键 copy 啦 el.addEventListener('click', el.handler); }, // 当传进来的值更新的时候触发 componentUpdated(el, { value }) { el.$value = value; }, // 指令与元素解绑的时候,移除事件绑定 unbind(el) { el.removeEventListener('click', el.handler); }, }); 使用方法 <el-dropdown-item v-auth.login="handleDownload" :authority="['download']" :msg="visitorMsg"> 下载原件 </el-dropdown-item>