useAutoResizeTextarea.ts 638 B

1234567891011121314151617181920212223
  1. import { ref, watch, onMounted } from 'vue';
  2. export function useAutoResizeTextarea(textareaRef: any, text: any) {
  3. const adjustHeight = () => {
  4. const textarea = textareaRef.value.ref;
  5. textarea.style.height = 'auto'; // 重置高度
  6. textarea.style.height = `${textarea.scrollHeight}px`; // 设置新高度
  7. textarea.style['max-height'] = '240px';
  8. textarea.style['min-height'] = '54px';
  9. };
  10. watch(text, (newVal) => {
  11. if (newVal === '') {
  12. textareaRef.value.ref.style.height = '54px';
  13. return;
  14. }
  15. adjustHeight();
  16. });
  17. onMounted(() => {
  18. adjustHeight(); // 初始化时调整高度
  19. });
  20. }