Skip to content

useTextareaAutosize

类别
导出体积
922 B
上次更改
1 hour 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
>

源码

源码演示文档

贡献者

一纸忘忧

更新日志

没有最近的更新日志