在vue中,让表格td下的textraea自适应高度

1.效果图

2.数据是动态获取的,因此存在一个异步的问题,解决的思路是数据获取到渲染在textarea中以后,获取文字的真实高度,然后把这个高度给textarea

3.具体代码以及步骤

(1)再created中调用,async是解决异步的一个机制

async created () {
 await this.getData()
 this.getHeight()
},

(2)methods中的js

// 获取最近数据
async getData () {
  await this.$axios.get(`地址}`, { checkToken: true }).then(res => {
    this.curWeekly = res.data
  })
},
// 改变高度
getHeight () {
  let textArea = document.getElementsByTagName('textarea')
  for (let i = 0; i < textArea.length; i++) {
    textArea[i].style.height = 'auto' // 先设置成auto,再设置高度,删除文字的时候高度才会改变
    textArea[i].style.height = textArea[i].scrollHeight + 'px'
  }
},

(3)html,是在td下面的textarea,textarea样式设置成想要的就行。

<td class="tdStyle1">
  <textarea type="text" id='textArea' v-model="curWeekly.curweekplan" @input="getHeight"></textarea>
</td>
<td class="tdStyle1">
  <textarea type="text" v-model="curWeekly.actual_final" @input="getHeight"></textarea>
</td>

无语,花了一天才研究出来。。

原文地址:https://www.cnblogs.com/wgl0126/p/10895875.html