vue实现文本超出字数时显示省略号
时间: 2023-09-06 19:07:08 浏览: 46
在 Vue 中实现文本超出字数时显示省略号,可以使用 CSS 的 `text-overflow: ellipsis` 属性。具体步骤如下:
1. 在 CSS 中设置需要显示省略号的元素的样式:
```css
.text-ellipsis {
white-space: nowrap; /* 不换行 */
overflow: hidden; /* 超出部分隐藏 */
text-overflow: ellipsis; /* 显示省略号 */
}
```
2. 在 Vue 模板中使用 `v-bind:class` 绑定样式类,并设置 `title` 属性为完整文本:
```html
<p v-bind:class="{ 'text-ellipsis': isOverflow }" title="完整文本">{{ text }}</p>
```
其中,`isOverflow` 是一个计算属性,用于判断文本是否超出,`text` 是需要显示的文本。
3. 在计算属性中计算文本是否超出:
```javascript
computed: {
isOverflow() {
const el = this.$el.querySelector('.text-ellipsis');
return el ? el.offsetWidth < el.scrollWidth : false;
}
}
```
使用 `querySelector` 获取元素,然后判断元素的实际宽度是否大于容器的宽度,如果大于就返回 `true`,否则返回 `false`。如果获取不到元素,就返回 `false`。
完整代码示例:
```html
<template>
<div>
<p v-bind:class="{ 'text-ellipsis': isOverflow }" title="完整文本">{{ text }}</p>
</div>
</template>
<script>
export default {
data() {
return {
text: '这是一段很长很长很长的文本,超过了容器宽度'
};
},
computed: {
isOverflow() {
const el = this.$el.querySelector('.text-ellipsis');
return el ? el.offsetWidth < el.scrollWidth : false;
}
}
};
</script>
<style>
.text-ellipsis {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
width: 100px;
border: 1px solid #ccc;
}
</style>
```