封装超出一行使用tooltip展示内容组件
很多情况都会出现超出一行就隐藏超出的内容,使用省略号代替,鼠标放上去要出现一个提示框展示所有的内容需求,下面我们就封装这样一个组件
html 代码
<template>
<div class="show-more-box">
<el-tooltip
ref="showMoreText"
class="show-more-text"
effect="dark"
enterable
:disabled="!showToolTip"
:popper-class="`tooltip-scroll ${toolTipSize === 'small' ? 'show-more-text_small' : ''}`"
:content="content"
:placement="toolTipPlacement"
>
<div slot="content" class="tooltip-content-scroll">
{{content}}
</div>
<p
class="show-more-text ellipsis"
>{{content}}</p>
</el-tooltip>
</div>
</template>
JS代码
<script>
export default {
name: 'showMreText',
props: {
content: {
type: [String, Object, Array, Number],
default: ''
},
// tooltip位置
toolTipPlacement: {
type: String,
default: 'bottom'
},
// tooltip尺寸,默认为-normal small为小尺寸
toolTipSize: {
type: String,
default: 'normal'
},
// 延迟设置tooltip是否显示,由于部分地方用到时,因为其他元素的影响,会改变内容宽度;默认是0
timer: {
type: Number,
default: 0
}
},
data () {
return {
showToolTip: false // 是否显示tooltip
}
},
watch: {
content: {
immediate: true,
handler () {
this.setShowToolTip()
}
}
},
mounted () {
this.setShowToolTip()
// 不能使用 window.onresize = () => {}
// 因为上面这种方法不能多个组件同时监听浏览器窗口大小发生变化
window.addEventListener('resize', this.windowResize)
},
methods: {
/**
* 设置是否显示toolTip
*/
setShowToolTip () {
this.$nextTick(() => {
setTimeout(() => {
let scrollWidth = this.$refs.showMoreText && this.$refs.showMoreText.$el ? this.$refs.showMoreText.$el.scrollWidth : 0
let offsetWidth = this.$refs.showMoreText && this.$refs.showMoreText.$el ? this.$refs.showMoreText.$el.offsetWidth : 0
this.showToolTip = scrollWidth > offsetWidth
}, this.timer)
})
},
// 窗口变化,判断是否显示省略文本
windowResize () {
this.setShowToolTip()
}
},
beforeDestroy () {
// 移除监听页面变化方法
window.removeEventListener('resize', this.windowResize)
}
}
</script>
csss 代码
<style lang="scss" scoped>
.show-more-box {
position: relative;
}
.show-more-text {
width: 100%;
word-break: break-word;
}
// 自定义内容,设置最高高度,多出部分滚动
.tooltip-content-scroll {
max-height: 184px!important;
overflow-y: auto;
padding-right: 5px;
// 内容部分滚动条样式调整
&::-webkit-scrollbar {
width: 3px;
}
&::-webkit-scrollbar-track,
&::-webkit-scrollbar-corner {
background: rgba(51, 51, 51, 0.9);
}
&::-webkit-scrollbar-thumb {
border-radius: 3px;
width: 3px;
background: #D5D5D5;
}
&::-webkit-scrollbar-track-piece {
background: rgba(51, 51, 51, 0.9);
width: 3px;
}
}
// 小号tooltip
.show-more-text_small {
font-size: 12px!important;
padding: 6px 5px!important;
line-height: 1.2!important;
border: none!important;
}
.tooltip-scroll {
padding-right: 5px!important;
}
//文字超出宽度显示省略号 单行
.ellipsis {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap
}
</style>
使用该组件
<show-more-text
v-if="scope.row.lawPerson"
:content="scope.row.lawPerson" // 要展示的内容
toolTipPlacement="top" // 轻提示的位置
></show-more-text>
效果图
这个组件已经封装完毕拉,希望能帮到小伙伴们!