You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue问题:textarea组件页面加载时无法根据初始内容自动调整高度

解决Vue Textarea初始内容自动调整高度的问题

嘿,这个问题我之前在开发Vue表单组件时也碰到过,咱们一步步来搞定它~

问题根源

你当前在mounted里用this.$el访问元素,大概率是因为**this.$el并没有指向你的textarea元素**。如果你的组件模板里还有其他元素(比如同时存在input和textarea的分支,或者外层有容器标签),this.$el会指向组件的根DOM元素,而不是你需要的textarea,自然就没法正确获取scrollHeight来调整高度了。

解决方案:用Ref精准定位textarea

最可靠的方式是给textarea添加ref属性,这样能直接拿到目标元素:

  1. 给textarea添加ref标识
    修改你的textarea标签,加上ref="textarea":
<textarea 
  v-if="$attrs.type === 'textarea'" 
  ref="textarea"  <!-- 新增ref定位 -->
  v-bind="$attrs" 
  :value="value" 
  @input="inputChange" 
  :class="[ 
    error ? 'text-red-500' : 'text-gray-600', 
    textareaAutoResized ? 'h-32' : '', 
    inputClass, 
  ]" 
></textarea>
  1. 在mounted中通过ref获取元素并调整高度
    修改你的mounted钩子,用this.$refs.textarea访问目标元素,同时加个存在性判断避免报错:
mounted() { 
  if (this.$attrs.type === 'textarea' && this.textareaAutoResized) { 
    const textarea = this.$refs.textarea;
    // 确保textarea已完成渲染
    if (textarea) {
      textarea.style.height = "auto"; 
      const newHeight = textarea.scrollHeight; 
      textarea.style.height = `${newHeight}px`; 
    }
  } 
}

额外优化:处理异步加载的初始值

如果你的value是异步获取的(比如从接口请求数据),mounted时可能还没拿到初始值,这时候需要监听value的变化,再重新调整高度:

watch: {
  value() {
    // 用$nextTick确保DOM已更新后再操作
    this.$nextTick(() => {
      if (this.$attrs.type === 'textarea' && this.textareaAutoResized) {
        const textarea = this.$refs.textarea;
        if (textarea) {
          textarea.style.height = "auto";
          textarea.style.height = `${textarea.scrollHeight}px`;
        }
      }
    });
  }
}

这样不管是页面加载时的初始值,还是后续异步更新的内容,textarea都能自动适配高度啦~

内容的提问来源于stack exchange,提问作者TheRealPapa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 20:07:29