Skip to content

useTextareaAutosize

类别
导出体积
869 B
上次更改
2 minutes ago

根据内容自动更新 textarea 的高度。

示例

输入内容,文本框会自动增长:

用法

简单示例

vue
<script setup lang="ts">
const { textarea, input } = useTextareaAutosize()
</script>

<template>
  <textarea
    ref="textarea"
    v-model="input"
    class="resize-none"
    placeholder="想说点什么?"
  />
</template>

INFO

建议重置 textarea 元素的滚动条样式,以避免大量文本导致的高度值不正确。

css
textarea {
  -ms-overflow-style: none;
  scrollbar-width: none;
}

textarea::-webkit-scrollbar {
  display: none;
}

使用 rows 属性

如果你需要在 textarea 元素上支持 rows 属性,则应将 styleProp 选项设置为 minHeight

vue
<script setup lang="ts">
const { textarea, input } = useTextareaAutosize({ styleProp: 'minHeight' })
</script>

<template>
  <textarea
    ref="textarea"
    v-model="input"
    class="resize-none"
    placeholder="What's on your mind?"
    rows="3"
  />
</template>

类型声明

typescript
export interface UseTextareaAutosizeOptions {
  /** 自动调整大小的文本区域元素。 */
  element?: MaybeRef<HTMLTextAreaElement | undefined>
  /** 文本区域的内容。 */
  input?: MaybeRef<string | undefined>
  /** 监听应触发文本区域大小调整的源。 */
  watch?: WatchSource | Array<WatchSource>
  /** 当文本区域大小发生变化时调用的函数。 */
  onResize?: () => void
  /** 指定样式目标以根据文本区域内容应用高度。如果未提供,将使用文本区域本身。 */
  styleTarget?: MaybeRef<HTMLElement | undefined>
  /** 指定用于调整高度的样式属性。可以是 `height | minHeight`。默认值为 `height`。 */
  styleProp?: "height" | "minHeight"
}
export declare function useTextareaAutosize(
  options?: UseTextareaAutosizeOptions,
): {
  textarea: Ref<HTMLTextAreaElement, HTMLTextAreaElement>
  input: Ref<string, string>
  triggerResize: () => void
}
export type UseTextareaAutosizeReturn = ReturnType<typeof useTextareaAutosize>

源码

源码演示文档

贡献者

一纸忘忧
Anthony Fu
Anthony Fu
Mutter
huiliangShen
yakudik
leex
JD Solanki
Dominik Pschenitschni
Jelf
Enzo Innocenzi

更新日志

v11.0.0-beta.2 on 7/17/2024
06c6f - fix: improve triggerResize triggering (#4074)
v10.10.0 on 5/27/2024
a6ede - fix: onResize callback fires not only on resize (#3887)
v10.8.0 on 2/20/2024
5025e - feat: allow configuring styleProp to support native rows attribute (#3552)
v10.2.0 on 6/16/2023
1b0ec - fix: autosize error when changing input asynchronously (#3118)
v10.0.0-beta.0 on 3/14/2023
a3e95 - feat: added styleTarget option to style other element (#2312)
v9.7.0 on 12/16/2022
ea497 - fix: reference
ebd48 - fix: support changes of element width (#2541)