Nuxt3+Tailwind CSS实现聊天输入框随内容动态增高至500px
解决Nuxt3+Tailwind聊天输入框自适应高度问题
核心实现思路
要实现textarea随内容自动增高且限制最大高度,同时让.chat-footer自适应高度,关键在于动态计算textarea的滚动高度,并确保父容器不设置固定高度。之前用ref修改高度无效,大概率是没在正确时机执行,或是没先重置高度为auto导致无法收缩。
方案一:Vue自定义指令(复用性高)
适合多个组件需要这个功能的场景,自定义指令可以全局注册或局部使用:
<template> <div class="chat-footer bg-gray-100 p-4"> <textarea ref="chatInput" v-auto-resize class="w-full p-3 border rounded-lg max-h-[500px] overflow-y-auto resize-none" placeholder="输入消息..." v-model="message" ></textarea> <button class="mt-2 px-4 py-2 bg-blue-500 text-white rounded">发送</button> </div> </template> <script setup> import { ref } from 'vue' const message = ref('') const chatInput = ref(null) // 局部注册自定义指令 const vAutoResize = { mounted(el) { // 初始化高度 el.style.height = 'auto' el.style.height = `${el.scrollHeight}px` // 绑定输入事件监听 el.addEventListener('input', handleResize) }, updated(el) { // 内容更新时重新调整 handleResize(el) }, unmounted(el) { // 组件销毁时移除监听 el.removeEventListener('input', handleResize) } } function handleResize(el) { // 先重置高度为auto,才能正确计算scrollHeight el.style.height = 'auto' // 限制最大高度为500px const targetHeight = Math.min(el.scrollHeight, 500) el.style.height = `${targetHeight}px` } </script>
方案二:直接绑定输入事件(快速实现)
如果只是单个组件使用,直接在textarea上绑定@input事件更简单:
<template> <div class="chat-footer bg-gray-100 p-4"> <textarea ref="chatInput" @input="resizeTextarea" class="w-full p-3 border rounded-lg max-h-[500px] overflow-y-auto resize-none" placeholder="输入消息..." v-model="message" ></textarea> <button class="mt-2 px-4 py-2 bg-blue-500 text-white rounded">发送</button> </div> </template> <script setup> import { ref, onMounted } from 'vue' const message = ref('') const chatInput = ref(null) function resizeTextarea() { const el = chatInput.value if (!el) return el.style.height = 'auto' const targetHeight = Math.min(el.scrollHeight, 500) el.style.height = `${targetHeight}px` } // 组件挂载时初始化高度 onMounted(resizeTextarea) </script>
关键注意事项
- 父容器
.chat-footer不要设固定高度:用默认的block布局或flex flex-col,它会自动根据textarea的高度撑开,无需额外调整。 - 必须先重置高度为
auto:如果直接设置scrollHeight,textarea内容减少时不会自动收缩,先设auto才能让浏览器重新计算高度。 - Tailwind类配置:
max-h-[500px]:限制textarea最大高度overflow-y-auto:内容超过最大高度时显示滚动条resize-none:禁用默认的拖动调整大小功能
内容的提问来源于stack exchange,提问作者MrFullstackDec
相关产品推荐
相关产品推荐

