跳到主要内容

useTextareaAutosize

分类
导出大小
922 B
上次更改
7 个月前

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

演示

输入时,文本区域会随之增长

用法

简单示例

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
="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">
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 {
  /** 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
>

来源

源文件演示文档

贡献者

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

更新日志

v12.8.0
7432f - feat(types): 废弃 MaybeRefMaybeRefOrGetter,转而使用 Vue 的原生类型 (#4636)
v12.7.0
e1a7e - 修复:使用 requestAnimationFrame 改进调整大小处理 (#4557)
v12.3.0
59f75 - feat(toValue): 废弃 @vueuse/shared 中的 toValue,转而使用 Vue 的原生函数
v12.1.0
25ed2 - 修复:使输入成为必需项 (#4129)
0a9ed - feat!: 放弃对 Vue 2 的支持,优化打包并清理 (#4349)
06c6f - 修复:改进 triggerResize 触发 (#4074)
a6ede - 修复:onResize 回调不仅在调整大小时触发 (#3887)
v10.8.0
5025e - 功能:允许配置 styleProp 以支持原生 rows 属性 (#3552)
v10.2.0
1b0ec - 修复:异步更改 input 时自动调整大小错误 (#3118)

根据 MIT 许可证发布。