import { createVNode, DirectiveBinding, ObjectDirective, render } from 'vue'; const SUCCESS = '#72c140'; const ERROR = '#ed5b56'; const WARNING = '#f0af41'; const INFO = '#4091f7'; const HEIGHT = 20; let flag = false; const Badge: ObjectDirective = { updated(el: HTMLElement, binding: DirectiveBinding) { const { modifiers, value } = binding; const modifiersKey = Object.keys(modifiers); const isDot = modifiersKey.includes('dot'); let backgroundColor = ''; if (modifiersKey.includes('success')) { backgroundColor = SUCCESS; } else if (modifiersKey.includes('warning')) { backgroundColor = WARNING; } else if (modifiersKey.includes('info')) { backgroundColor = INFO; } else { backgroundColor = ERROR; } const targetTemplate = isDot ? `
` : `
${value}
`; el.style.position = el.style.position || 'relative'; //将options参数传入,并将badge组件转换成虚拟DOM,并赋值给app const badge = createVNode({ template: targetTemplate, }); //创建一个空的span const mountNode = document.createElement('span'); mountNode.className = 'ibiz-badge'; //render函数的作用就是将badge组件的虚拟DOM转换成真实DOM并插入到mountNode元素里 render(badge, mountNode); if (value) { if (flag && el.lastChild) { el.removeChild(el.lastChild); } el.appendChild(mountNode); flag = true; } }, }; export default Badge;