textellipsis.vue
2.23 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
<template>
<div class="h-text-ellipsis" :style="{width: width ? width + 'px': 'unset'}">
<slot name="before" class="h-text-ellipsis-before"></slot>
<span class="text-ellipsis-limit-text" :key="keyIndex" :content="text">{{text}}</span>
<span class="h-text-ellipsis-more" v-show='oversize'><slot name="more"></slot></span>
<slot name="after" class="h-text-ellipsis-after"></slot>
</div>
</template>
<script>
export default {
name: 'TextEllipsis',
props: {
text: String,
height: Number,
width: {
Number,
default: 0
},
isLimitHeight: {
type: Boolean,
default: true
}
},
data() {
return {
keyIndex: 0,
oversize: false,
isHide: false
};
},
watch: {
isLimitHeight() {
this.init();
},
text() {
this.init();
},
height() {
this.init();
},
width() {
this.init();
}
},
mounted() {
this.init();
},
methods: {
init() {
this.oversize = false;
this.keyIndex += 1;
let more = this.$el.querySelector('.h-text-ellipsis-more');
more.style.display = 'none';
if (this.isLimitHeight) {
this.limitShow();
}
},
limitShow() {
this.$nextTick(() => {
let textDom = this.$el.querySelector('.text-ellipsis-limit-text');
let title = this.$el;
let more = this.$el.querySelector('.h-text-ellipsis-more');
let n = 1000;
if (textDom) {
if (title.offsetHeight > this.height) {
more.style.display = 'inline-block';
let text = this.text;
while (title.offsetHeight > this.height && n > 0) {
if (title.offsetHeight > this.height * 3) {
textDom.innerText = text = text.substring(0, Math.floor(text.length / 2));
} else {
textDom.innerText = text = text.substring(0, text.length - 1);
}
n--;
}
this.$emit('hide');
this.isHide = true;
} else {
this.$emit('show');
this.isHide = false;
}
}
});
}
}
};
</script>
<style lang="scss" scoped>
.text-ellipsis-limit-text {
white-space: pre-wrap;
}
</style>