vue 自定义指令
项目中使用指令的情景是“有无权限”
// 指令的代码
Vue.directive('pIndex', {
bind (el,binding, vnode) {
var clientType = getCookie("clientType") || "PC";
if(!Vue.prototype.$permissions(binding.value)){
const tSpan = document.createElement('span');
tSpan.innerHTML = '无访问权限';
el.appendChild(tSpan);
tSpan.style.color = 'rgb(204, 204, 204)';
tSpan.style.fontSize = clientType == "PC" ? "16px" : "12px";
tSpan.style.visibility = 'visible';
el.className += ' no-permissions-single'
const curStyle = window.getComputedStyle(el, '') // 获取当前元素的style
const textSpan = document.createElement('span') // 创建一个容器来记录文字的width
// 设置新容器的字体样式,确保与当前需要隐藏的样式相同
textSpan.style.fontSize = curStyle.fontSize
textSpan.style.fontWeight = curStyle.fontWeight
textSpan.style.fontFamily = curStyle.fontFamily
// 将容器插入body,如果不插入,offsetWidth为0
document.body.appendChild(textSpan)
// 设置新容器的文字
textSpan.innerHTML = el.innerText
// 如果字体元素大于当前元素,则需要隐藏
if (textSpan.offsetWidth > el.offsetWidth) {
// 给当前元素设置超出隐藏
el.style.overflow = 'hidden'
el.style.textOverflow = 'ellipsis'
el.style.whiteSpace = 'nowrap'
// 鼠标移入
tSpan.onmouseenter = function (e) {
// 创建浮层元素并设置样式
const vcTooltipDom = document.createElement('div')
vcTooltipDom.style.cssText = `
overflow: auto;
position:absolute;
top: ${e.clientY}px;
left:${e.clientX-10}px;
padding-left:10px;
background: rgba(0, 0 , 0, .6);
color: #fff;
border-radius:5px;
padding:8px;
display:inline-block;
font-size:12px;
z-index:19999;
pointer-events: none;
`
// 设置id方便寻找
vcTooltipDom.setAttribute('id', 'vc-tooltip')
// 将浮层插入到body中
document.body.appendChild(vcTooltipDom)
// 浮层中的文字
document.getElementById('vc-tooltip').innerHTML = '暂无权限,如申请权限,请提交IT服务热线申请(拨打电话010-59568666或访问itsm@sinochem.com)'
}
// 鼠标移出
tSpan.onmouseleave = function () {
// 找到浮层元素并移出
const vcTooltipDom = document.getElementById('vc-tooltip')
vcTooltipDom && document.body.removeChild(vcTooltipDom)
}
}
// 记得移除刚刚创建的记录文字的容器
document.body.removeChild(textSpan)
}
},
// 指令与元素解绑时
unbind () {
// 找到浮层元素并移除
const vcTooltipDom = document.getElementById('vc-tooltip')
vcTooltipDom && document.body.removeChild(vcTooltipDom)
}
})
// 公共权限的方法
Vue.prototype.$permissions = function(code){
const RIGHTLIST = window.localStorage.getItem('RIGHTLIST');
if(RIGHTLIST != 'undefined' && RIGHTLIST && RIGHTLIST != 'null'){
let permissionsNew = JSON.parse(RIGHTLIST);
let permissions = permissionsNew.map((item,index) =>{
return item.fieldId;
});
return permissions.includes(code)
}else{
return true;
}
};
自定义指令的介绍
钩子函数:
一个指令定义对象可以提供如下几个钩子函数
bind:只调用一次,指令第一次绑定到元素时调用。
inserted:被绑定元素插入父节点时调用。
update:所在组件的VNode更新时调用,但是可能发生在其子VNode更新前。
还没有评论,来说两句吧...