Created
November 15, 2021 08:39
-
-
Save lorisleiva/a58937c34a934ef7d5e391548ca032fe to your computer and use it in GitHub Desktop.
Auto-resize a textarea based on its content (Vue 3 composition API)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { watchEffect } from "vue" | |
export const useAutoresizeTextarea = (element) => { | |
const resizeTextarea = () => { | |
element.value.style.height = 'auto' | |
element.value.style.height = element.value.scrollHeight + 'px' | |
} | |
watchEffect(onInvalidate => { | |
if (! element.value) return | |
resizeTextarea() | |
element.value.addEventListener('input', resizeTextarea) | |
onInvalidate(() => element.value?.removeEventListener('input', resizeTextarea)) | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment