Lzh on GitHub

根据内容自动更新文本区域(textarea)的高度。

Demo

使用

简单例子

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

<template>
  <textarea
    ref="textarea"
    v-model="input"
    class="resize-none"
    placeholder="What's on your mind?"
  />
</template>
建议重置文本区域 (textarea) 元素的滚动条样式,以避免在文本量大时出现不正确的高度值。
textarea {
  -ms-overflow-style: none;
  scrollbar-width: none;
}

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

带有 rows 属性

如果你需要在文本区域 (textarea) 元素上支持 rows 属性,那么你应该将 styleProp 选项设置为 minHeight

<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>

类型声明

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>