Skip to content

useTextareaAutosize

Category
Export Size
779 B
Last Changed
2 days ago

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

Demo

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

用法

简单示例

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>

Type Declarations

Show Type Declarations
typescript
export interface UseTextareaAutosizeOptions extends ConfigurableWindow {
  /** Textarea element to autosize. */
  element?: MaybeRef<HTMLTextAreaElement | undefined | null>
  /** Textarea content. */
  input?: MaybeRef<string>
  /** Watch sources that should trigger a textarea resize. */
  watch?: WatchSource | Array<WatchSource>
  /** Function called when the textarea size changes. */
  onResize?: () => void
  /** Specify style target to apply the height based on textarea content. If not provided it will use textarea it self.  */
  styleTarget?: MaybeRef<HTMLElement | undefined>
  /** Specify the style property that will be used to manipulate height. Can be `height | minHeight`. Default value is `height`. */
  styleProp?: "height" | "minHeight"
}
export declare function useTextareaAutosize(
  options?: UseTextareaAutosizeOptions,
): {
  textarea: Ref<
    HTMLTextAreaElement | null | undefined,
    HTMLTextAreaElement | null | undefined
  >
  input: Ref<string, string>
  triggerResize: () => void
}
export type UseTextareaAutosizeReturn = ReturnType<typeof useTextareaAutosize>

Source

SourceDemoDocs

Contributors

丶远方
Anthony Fu
IlyaL
Anthony Fu
Nikola Begedin
axuj
Mutter
huiliangShen
yakudik
leex
JD Solanki
Dominik Pschenitschni
Jelf
Enzo Innocenzi

Changelog

7432f - feat(types): deprecate MaybeRef and MaybeRefOrGetter in favor of Vue's native (#4636)
e1a7e - fix: improve resize handling with requestAnimationFrame (#4557)
59f75 - feat(toValue): deprecate toValue from @vueuse/shared in favor of Vue's native
25ed2 - fix: make input required (#4129)
0a9ed - feat!: drop Vue 2 support, optimize bundles and clean up (#4349)
06c6f - fix: improve triggerResize triggering (#4074)
a6ede - fix: onResize callback fires not only on resize (#3887)
5025e - feat: allow configuring styleProp to support native rows attribute (#3552)
1b0ec - fix: autosize error when changing input asynchronously (#3118)

Released under the MIT License.