コンテンツにスキップ

useTextareaAutosize

カテゴリ
エクスポートサイズ
869 バイト
最終更新日
先週

コンテンツに応じてテキストエリアの高さを自動的に更新します。

デモ

入力すると、テキストエリアが拡大します

使用方法

簡単な例

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

情報

大量のテキストに対して高さの値が正しく計算されないのを避けるため、テキストエリア要素のスクロールバースタイルをリセットすることをお勧めします。

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

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

rows属性を使用する場合

テキストエリア要素で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 {
  /** Textarea element to autosize. */
  element?: MaybeRef<HTMLTextAreaElement | undefined>
  /** Textarea content. */
  input?: MaybeRef<string | undefined>
  /** 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, 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

変更履歴

v12.0.0-beta.1 2024/11/21
0a9ed - feat!: Vue 2 のサポートを終了し、バンドルを最適化し、クリーンアップ (#4349)
v11.0.0-beta.2 2024/7/17
06c6f - 修正: triggerResize のトリガーを改善 (#4074)
v10.10.0 2024/5/27
a6ede - 修正: onResize コールバックがリサイズ時以外にも発火する (#3887)
v10.8.0 2024/2/20
5025e - 機能: ネイティブの rows 属性をサポートするために styleProp を設定できるようにする (#3552)
v10.2.0 2023/6/16
1b0ec - 修正: input を非同期で変更すると autosize エラーが発生する (#3118)
v10.0.0-beta.0 2023/3/14
a3e95 - 機能: 別の要素をスタイル設定するための styleTarget オプションを追加 (#2312)
v9.7.0 2022/12/16
ea497 - 修正: 参照
ebd48 - 修正: 要素の幅の変更をサポート (#2541)

MITライセンスでリリースされています。