使用vue3自定义指令实现Tooltip

效果预览:

使用vue3自定义指令实现Tooltip_第1张图片

 

实现代码:

directive.js

import { nextTick } from "vue"

function elFover(e) {

	// e.el.classList.add('hover')

	let res = e.el.getBoundingClientRect()
	// console.log(res)

	let dom_tooltip = document.querySelector('.c-tooltip')
	
	if(dom_tooltip) {
		dom_tooltip.style.display = 'block'
		dom_tooltip.querySelector('.ivu-tooltip-inner').innerText = e.val
	
	} else {
		let _div = document.createElement('div')
		_div.innerHTML = `
${e.val}
` document.body.appendChild(_div) } nextTick(() => { !dom_tooltip && (dom_tooltip = document.querySelector('.c-tooltip')) let _res = dom_tooltip.getBoundingClientRect() if(res.top < _res.height) { dom_tooltip.style.top = res.bottom +'px' dom_tooltip.setAttribute('x-placement', 'bottom') } else { dom_tooltip.style.top = (res.top - _res.height) +'px' dom_tooltip.setAttribute('x-placement', 'top') } if(res.left < (_res.width - res.width)/2) { dom_tooltip.style.left = 0 +'px' } else if(window.innerWidth - res.right < (_res.width - res.width)/2) { dom_tooltip.style.left = (window.innerWidth - _res.width) +'px' } else { dom_tooltip.style.left = (res.left + (res.width - _res.width)/2) +'px' } }) } function elLeave() { let dom_tooltip = document.querySelector('.c-tooltip') if(dom_tooltip) { dom_tooltip.style.display = 'none' } } let fb = undefined export const vFocus = { mounted: (el, binding) => { fb = elFover.bind(this, { el: el, val: binding.value }) el.addEventListener('mouseenter', fb) el.addEventListener('mouseleave', elLeave) }, // 绑定元素的父组件卸载前调用 beforeUnmount(el, binding, vnode, prevVnode) { el.removeEventListener('mouseenter', fb) el.removeEventListener('mouseleave', elLeave) }, }

main.ts

import { vFocus } from '@/utils/directive.js'
import { createApp } from 'vue'

const app = createApp(App)
app.directive('focus', vFocus)

组件里使用

你可能感兴趣的:(Vue,javascript,vue.js,前端)