useTextareaAutosize
根据内容自动更新 textarea 的高度。
演示
输入文本,textarea 将会增长
用法
简单示例
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>
注意
建议重置 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">
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 extends ConfigurableWindow {
/** Textarea element to autosize. */
element?: MaybeRef<HTMLTextAreaElement | undefined>
/** 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 | undefined,
HTMLTextAreaElement | undefined
>
input: Ref<string, string>
triggerResize: () => void
}
export type UseTextareaAutosizeReturn = ReturnType<typeof useTextareaAutosize>
源代码
贡献者
更新日志
v12.8.0
on 3/5/2025v12.7.0
on 2/15/2025v12.3.0
on 1/2/202559f75
- feat(toValue): deprecate toValue
from @vueuse/shared
in favor of Vue's nativev12.1.0
on 12/22/2024v12.0.0-beta.1
on 11/21/2024v11.0.0-beta.2
on 7/17/2024v10.10.0
on 5/27/2024v10.8.0
on 2/20/2024v10.2.0
on 6/16/2023v10.0.0-beta.0
on 3/14/2023