Vue 通过 VueUse 的 useTextareaAutosize 实现 textarea 文本域自适应高度,当然输入的文字内容超过 textarea 默认高度时会自动撑开该元素的高度。
<script setup lang="ts">
import { useTextareaAutosize } from '@vueuse/core'
const { textarea, input } = useTextareaAutosize()
</script>
<template>
<textarea
ref="textarea"
v-model="input"
placeholder="输入多点的文字试试看?"
/>
</template>
例子
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>
}
export declare function useTextareaAutosize(
options?: UseTextareaAutosizeOptions,
): {
textarea: Ref<HTMLTextAreaElement>
input: Ref<string>
triggerResize: () => void
}
export type UseTextareaAutosizeReturn = ReturnType<typeof useTextareaAutosize>