Vue中可根據內容自適應改變高度的textarea文本框
如圖所示,當
textarea
里的內容超過一行后,會出現滾動條並隱藏前一行的內容,特別是在移動端使用到textarea多行文本輸入的話,這樣顯示其實是很不友好的。所以要做一個可根據內容改變高度的textarea的組件。

踩坑嘗試
利用rows
屬性來改變高度:

W3C HTML <textarea> 標簽
踩坑時的思路:
- 給
textarea
加上rows
屬性,並雙向綁定在data
的rows
上。如:<textarea ref="textarea" :rows="rows" v-model="value" class="textarea"></textarea> - 獲取初始頁面時候
textarea
的高度,這就是一行的高度oneHeight
; - 通過
vue
的watch
數據監聽,當textarea
的內容發生變化時觸發,獲取textarea
的scrollHeight
,再除以oneHeight
求整數然后加一就是rows
的數量。
踩坑感想:
這樣做是可以實現當內容變多,行數跟着變多的情況的,但是,當內容變少,scrollHeight
是不會減少的!所以rows
也不會變,一旦被撐大,就再也縮不回去。。。。顯然,這不是我想要的效果。
正確姿勢
猛然回想起ElementUI上就有可根據內容調整高度的組件ElementUI input!
然后就去扒源碼看看是怎么實現的,結果都已經封裝好了,太棒了,直接下載來引用就行了!
餓了么組件的源碼github地址:
https://github.com/ElemeFE/element/blob/dev/packages/input/src/calcTextareaHeight.js
下面是引用了ElementUI
的input
組件的calcTextareaHeight
方法的MyTextarea.vue
:
1 <template> 2 <div class="my-textarea"> 3 <textarea ref="textarea" :style="{'height': height}" v-model="value" class="textarea" ></textarea> 4 </div> 5 </template> 6 7 <script> 8 import calcTextareaHeight from '@/assets/calcTextareaHeight'; 9 10 export default { 11 name: 'my-textarea', 12 data() { 13 return { 14 // textarea內容 15 value: '', 16 // 動態高度 17 height: '30px' 18 } 19 }, 20 watch: { 21 value() { 22 this.getHeight(); 23 } 24 }, 25 methods: { 26 getHeight() { 27 this.height = calcTextareaHeight(this.$refs.textarea, 1, null).height; 28 } 29 } 30 } 31 </script> 32 33 <style scoped> 34 .my-textarea .textarea { 35 display: inline-block; 36 width: 400px; 37 /*height: 30px;*/ 38 line-height: 30px; 39 font-size: 30px; 40 resize: none; 41 } 42 </style>