Skip to content

useTextareaAutosize

类别
导出体积
922 B
上次更改
6 months ago

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

示例

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

用法

简单示例

vue
<script setup lang="ts">
import { 
useTextareaAutosize
} from '@vueuse/core'
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">
import { 
useTextareaAutosize
} from '@vueuse/core'
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>

类型声明

ts
export interface UseTextareaAutosizeOptions extends ConfigurableWindow {
  /** 自动调整大小的文本区域元素。 */
  
element
?:
MaybeRef
<HTMLTextAreaElement | undefined | null>
/** 文本区域的内容。 */
input
?:
MaybeRef
<string>
/** 监听应触发文本区域大小调整的源。 */
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 | null | undefined, HTMLTextAreaElement | null | undefined >
input
:
Ref
<string, string>
triggerResize
: () => void
} export type
UseTextareaAutosizeReturn
=
ReturnType
<typeof
useTextareaAutosize
>

源码

源码演示文档

贡献者

一纸忘忧
Anthony Fu
IlyaL
Anthony Fu
SerKo
Nikola Begedin
axuj
Mutter
huiliangShen
yakudik
leex
JD Solanki
Dominik Pschenitschni
Jelf
Enzo Innocenzi

更新日志

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)