typescript Vue3 onMounted无法刷新页面

k10s72fa  于 7个月前  发布在  TypeScript
关注(0)|答案(1)|浏览(150)

我有一个函数,检查文本是否被截断,如果是,则显示一个按钮来展开隐藏的文本。
我已经设置了一个完整的详细代码演示,我没有任何错误,但逻辑似乎不工作。任何指导将不胜感激。
我是说,

const information = ref<HTMLElement | null>(null)

onMounted(() => {
  // initialize 'information' ref status
  informationRefStatus()
})

function informationRefStatus() {
  if (information.value) {
    const element = information.value
    return isTextTruncated.value = element.scrollHeight > element.clientHeight
  }
}

字符串
模板:

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


CODE DEMO

0x6upsns

0x6upsns1#

这个问题缺少重要的部分:

<script>
...
const information = ref<HTMLElement | null>(null)

字符串
script标记使ref < HTMLElement | null > null被解析为JavaScript表达式,这是偶然有效的,并导致information在没有语法错误的情况下不是Vue ref。
它应该是:

<script lang="ts">
...

相关问题