如圖所示,當(dāng)textarea里的內(nèi)容超過(guò)一行后,會(huì)出現(xiàn)滾動(dòng)條并隱藏前一行的內(nèi)容,特別是在移動(dòng)端使用到textarea多行文本輸入的話,這樣顯示其實(shí)是很不友好的。所以要做一個(gè)可根據(jù)內(nèi)容改變高度的textarea的組件。

踩坑嘗試
利用rows屬性來(lái)改變高度:

W3C HTML <textarea> 標(biāo)簽
踩坑時(shí)的思路:
- 給
textarea加上rows屬性,并雙向綁定在data的rows上。(<textarea ref="textarea" :rows="rows" v-model="value" class="textarea" ></textarea>); - 獲取初始頁(yè)面時(shí)候
textarea的高度,這就是一行的高度oneHeight; - 通過(guò)
vue的watch數(shù)據(jù)監(jiān)聽,當(dāng)textarea的內(nèi)容發(fā)生變化時(shí)觸發(fā),獲取textarea的scrollHeight,再除以oneHeight求整數(shù)然后加一就是rows的數(shù)量。
踩坑感想:
這樣做是可以實(shí)現(xiàn)當(dāng)內(nèi)容變多,行數(shù)跟著變多的情況的,但是,當(dāng)內(nèi)容變少,scrollHeight是不會(huì)減少的!所以rows也不會(huì)變,一旦被撐大,就再也縮不回去。。。。顯然,這不是我想要的效果。
正確姿勢(shì)
猛然回想起ElementUI上就有可根據(jù)內(nèi)容調(diào)整高度的組件ElementUI input!
然后就去扒源碼看看是怎么實(shí)現(xiàn)的,結(jié)果都已經(jīng)封裝好了,太棒了,直接下載來(lái)引用就行了!
餓了么組件的源碼github地址:
https://github.com/ElemeFE/element/blob/dev/packages/input/src/calcTextareaHeight.js
下面是引用了ElementUI的input組件的calcTextareaHeight方法的MyTextarea.vue:
<template>
<div class="my-textarea">
<textarea ref="textarea" :style="{'height': height}" v-model="value" class="textarea" ></textarea>
</div>
</template>
<script>
import calcTextareaHeight from '@/assets/calcTextareaHeight';
export default {
name: 'my-textarea',
data() {
return {
// textarea內(nèi)容
value: '',
// 動(dòng)態(tài)高度
height: '30px'
}
},
watch: {
value() {
this.getHeight();
}
},
methods: {
getHeight() {
this.height = calcTextareaHeight(this.$refs.textarea, 1, null).height;
}
}
}
</script>
<style scoped>
.my-textarea .textarea {
display: inline-block;
width: 400px;
/*height: 30px;*/
line-height: 30px;
font-size: 30px;
resize: none;
}
</style>

無(wú)論是單個(gè)輸入或刪減,還是一段輸入或刪減,都能立刻自適應(yīng)改變高度