You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue3 onMounted页面刷新失效:文本截断判断逻辑无报错但不生效求助

文本截断检测功能修复方案

问题排查

你的代码逻辑无法正常运行主要有三个核心问题:

  • 类名绑定逻辑倒置:模板里的截断类绑定写反了,展开状态下不该加truncate类,收起时才需要。
  • 检测时机不完整:仅在组件挂载时执行检测,如果文本是异步加载的,挂载阶段DOM还没渲染出完整内容,检测结果会出错;另外窗口尺寸变化时,文本是否截断的状态也会改变,没做重新检测。
  • 状态联动缺失:切换展开/收起后,没有同步更新截断检测的状态,导致按钮显示逻辑混乱。

修复后的完整代码

Script 部分

<script setup lang="ts">
import { ref, onMounted, watch, nextTick } from 'vue'

// 模拟异步数据,实际项目中可能是接口返回
const data = ref({
  information: '这里是一段较长的测试文本,用于验证文本截断检测功能是否正常工作。当文本内容超过容器高度时,应该显示展开按钮,点击后可以查看完整内容,再次点击则收起。'
})

const information = ref<HTMLElement | null>(null)
const isExpanded = ref(false)
const isTextTruncated = ref(false)
const toggleCtaLabel = ref('展开')

// 检测文本是否截断的核心函数
function checkTextTruncated() {
  if (!information.value) return
  const element = information.value
  // 只有收起状态下才需要检测是否截断
  isTextTruncated.value = !isExpanded.value && element.scrollHeight > element.clientHeight
}

onMounted(() => {
  // 等待挂载后DOM渲染完成再检测
  nextTick(checkTextTruncated)
  // 窗口大小变化时重新检测
  window.addEventListener('resize', checkTextTruncated)
})

// 监听文本内容变化,异步加载完成后重新检测
watch(() => data.value.information, () => {
  nextTick(checkTextTruncated)
})

// 监听展开状态变化,同步更新按钮文本和检测状态
watch(isExpanded, (newStatus) => {
  toggleCtaLabel.value = newStatus ? '收起' : '展开'
  checkTextTruncated()
})
</script>

Template 部分

<template>
  <div class="text-wrapper">
    <div 
      ref="information" 
      :class="isExpanded ? '' : 'truncate'"
      class="text-content"
    >
      {{ data?.information }}
    </div>
    <span
      v-if="isTextTruncated"
      @click="isExpanded = !isExpanded"
      class="toggle-btn"
    >
      {{ toggleCtaLabel }}
    </span>
  </div>
</template>

Style 部分(补充必要样式)

<style scoped>
.text-wrapper {
  width: 300px;
  margin: 20px;
}

.text-content {
  line-height: 1.5;
  max-height: 4.5em; /* 对应3行文本高度,可按需调整 */
  overflow: hidden;
}

.truncate {
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 3; /* 限制显示行数 */
}

.toggle-btn {
  color: #1890ff;
  cursor: pointer;
  margin-top: 8px;
  display: inline-block;
}
</style>

修复说明

  1. 修正类名绑定:把:class="isExpanded ? 'truncate' : ''"改成:class="isExpanded ? '' : 'truncate'",确保收起状态下才启用文本截断样式。
  2. 完善检测时机:
    • 用nextTick确保DOM完全渲染后再执行检测,避免异步数据未加载导致的误判。
    • 监听文本内容变化,数据更新后自动重新检测。
    • 添加窗口resize事件监听,适配不同屏幕尺寸下的截断状态。
  3. 优化状态联动:监听展开状态的变化,同步更新按钮文本和截断检测结果,保证逻辑一致性。

内容的提问来源于stack exchange,提问作者Pianoc

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 20:12:47