vue实现搜索记录只显示两行 超出两行内容隐藏并显示展开按钮
    		       		warning:
    		            这篇文章距离上次修改已过447天,其中的内容可能已经有所变动。
    		        
        		                
                在Vue中,你可以通过计算属性来决定是否显示更多的文本,并且使用CSS来控制文本的样式,如超出两行后隐藏,并在末尾显示一个展开按钮。
以下是一个简单的示例:
<template>
  <div>
    <p :class="{ 'text-ellipsis': isExpanded }">
      {{ text }}
    </p>
    <button v-if="!isExpanded && truncatedText" @click="isExpanded = true">
      展开
    </button>
  </div>
</template>
 
<script>
export default {
  data() {
    return {
      isExpanded: false,
      originalText: '这里是需要显示的长文本内容,可以是搜索记录等。'
    };
  },
  computed: {
    text() {
      return this.isExpanded ? this.originalText : this.truncatedText;
    },
    truncatedText() {
      const lines = this.originalText.split('\n');
      const truncated = [];
      let lineCount = 0;
      for (const line of lines) {
        const height = line.length * 16; // 16px is the default line-height
        if (lineCount * height < 48) { // 48px is 2 lines
          truncated.push(line);
          lineCount++;
        } else {
          break;
        }
      }
      return truncated.join('\n');
    }
  }
};
</script>
 
<style>
.text-ellipsis {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
}
</style>在这个例子中,.text-ellipsis 类使得 <p> 标签内的文本在超过两行后隐藏,并以省略号显示。点击展开按钮会显示完整的文本内容。这里假设文本的行高为16px,如果需要调整为其他行高或者行数,请相应调整计算逻辑。
评论已关闭