检查线夹是否有vue组件的正确方法

gcxthw6b  于 7个月前  发布在  Vue.js
关注(0)|答案(1)|浏览(112)

这个问题完全符合我想做的,检查文本是否被截断或不How can I check whether line-clamp is enabled?。我知道这是不正确的,我真的很感激任何方向,让这个工作。
脚本

const isExpanded = ref(true);
const isTextTruncated = ref(true);
const toggleCta = computed(() =>   isExpanded.value ? 'show' : 'hide' )
const information = ref(true);
const isTextTruncated = computed(() => {
  const textLineCount = information.getClientRects().length;
  const lineClampValue = information.css('-webkit-line-clamp');
  if (textLineCount > lineClampValue) {
    return true
  }
})

模板

<div ref="information" :class="isExpanded ? 'truncate': ''">
  {{ data?.information }}
</div>
<span
  v-if="isTextTruncated"
  @click="isExpanded = !isExpanded"
>
  {{ toggleCta }}
</span>


风格

.truncate {
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
}


我试过How can I check whether line-clamp is enabled?

py49o6xq

py49o6xq1#

在你的Vue.js代码中,你试图检查是否在一个元素上启用了-webkit-line-clamp CSS属性。你走在正确的轨道上,但是你的代码中有一些问题需要解决。
1.信息应该是对DOM元素的引用,而不是布尔值。你可以使用ref来引用DOM元素。
1.您正在尝试使用information.css('-webkit-line-clamp')访问-webkit-line-clamp属性,但这不是在Vue.js中获取CSS属性值的正确方法。您应该使用window.getComputedStyle访问元素的计算样式。
试试这个
脚本

const isExpanded = ref(true);
const information = ref(null); // Initialize to null
const isTextTruncated = ref(false);

const toggleCta = computed(() => isExpanded.value ? 'show' : 'hide');

watch(information, () => {
  // Use watch to monitor changes in the 'information' ref
  const element = information.value;
  if (element) {
    const computedStyle = window.getComputedStyle(element);
    const lineClampValue = computedStyle.getPropertyValue('-webkit-line-clamp');
    const textLineCount = element.getClientRects().length;
    isTextTruncated.value = textLineCount > lineClampValue;
  }
});

字符串
模板:

<div ref="information" :class="isExpanded ? 'truncate' : ''">
  {{ data?.information }}
</div>
<span
  v-if="isTextTruncated"
  @click="isExpanded = !isExpanded"
>
  {{ toggleCta }}
</span>

相关问题