vue3 + textarea实现高度自适应
<template>
<textarea ref="textareaRef" v-model="content" class="my-textarea" :rows="rows"/>
</template>
<script>
import {ref, watch, nextTick, onMounted} from 'vue'
export default {
name: 'MyTextarea',
components: {
},
setup (props, {emit}) {
const textareaRef = ref(null);
const rows = ref(1)
const content = ref('')
onMounted(() => {
nextTick(adjustTextareaSize);
});
watch(() => content.value, () => {
nextTick(adjustTextareaSize);
})
const adjustTextareaSize = () => {
let textarea = textareaRef.value
textarea.style.height = 'auto';
const height = textarea.scrollHeight;
if (height) {
textarea.style.height = height + "px";
}
}
return {
textareaRef,
rows,
content
}
}
}
</script>