Vue.directive自定义指令
Vue.directive 自定义指令 el-tooptip 提示框
该指令主要实现 el-tooptip 提示框 自适应内容宽度是否溢出父元素, 且只有在当前元素宽度溢出父元素的情况下才回显示 el-tooltip
- 安装对应的vue项目依赖
- 安装element-ui 中的 Tooptip依赖;
具体代码
import Vue from 'vue'
import { getStyle } from 'element-ui/src/utils/dom'
/**
* 当text没有被折叠时或溢出父元素内容时,不显示tooltip
*/
const OurAutoTooltips = {
inserted: function (el, binding, vnode) {
el.addEventListener('mouseenter', function (e) {
const defalutSilent = !!Vue.config.silent
Vue.config.silent = true // 取消 Vue 所有的日志与警告
vnode.componentInstance.disabled = true // 禁用 el-tooltip
const range = document.createRange() // 创建 Range
range.setStart(el, 0) // 设置 Range 起点
range.setEnd(el, el.childNodes.length) // 设置 Range 终点
const rangeWidth = Math.round(range.getBoundingClientRect().width) // 获取当前元素相对于 浏览器视窗(可见区域) 的位置信息
// 获取当前 el-tooltip 的 x 轴 padding 值
const padding = (parseInt(getStyle(el, 'paddingLeft'), 10) || 0) + (parseInt(getStyle(el, 'paddingRight'), 10) || 0)
// 判断 Range 宽度 + 获取当前 el-tooltip 的 x 轴 padding 值 是否大于 el-tooltip 的 offsetWidth
if (rangeWidth + padding > el.offsetWidth || el.scrollWidth > el.offsetWidth) {
vnode.componentInstance.disabled = false // 启用 el-tooltip
}
Vue.config.silent = defalutSilent // 启用 Vue 所有的日志与警告
})
}
}
export default { name: 'our-tooltip', optionObj: OurAutoTooltips } // name: 指令名称 optionObj: 指令配置对象
- 批量注册自定义指令
// 批量注册自定义指令
const Directives = require.context('./', true, /\.js$/) // 获取当前路径下的所有 js 文件
export default {
install(app) {
Directives.keys().forEach(item => {
const DirectiveObj = Directives(item).default // 获取 js 文件默认导出项
app.directive(DirectiveObj.name, DirectiveObj.optionObj) // app.directive('自定义指令名称', '配置对象')
})
}
}
- 在main.js中注册指令
import GolbalDirectives from '@/directives/index.js' // 全局自定义指令
Vue.use(GolbalDirectives )
- 使用案例
<el-tooltip v-our-tooltip effect="dark" :content="row.remark" placement="top">
<div class="content single-line-ellipsis">{{ row.remark }}</div>
</el-tooltip>
Vue自定义Tooltip
本文介绍了一个Vue自定义指令el-tooptip,该指令能够根据内容宽度自动调整提示框的显示状态,防止溢出父元素。通过监听鼠标悬停事件来判断内容是否超出,并据此启用或禁用提示框。
1115

被折叠的 条评论
为什么被折叠?



