Vue中可根據內容自適應改變高度的textarea文本框


Vue中可根據內容自適應改變高度的textarea文本框

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

踩坑嘗試

利用rows屬性來改變高度:

 
W3C HTML <textarea> 標簽

踩坑時的思路:

  • textarea加上rows屬性,並雙向綁定在datarows上。如:<textarea ref="textarea" :rows="rows" v-model="value" class="textarea"></textarea>
  • 獲取初始頁面時候textarea的高度,這就是一行的高度oneHeight
  • 通過vuewatch數據監聽,當textarea的內容發生變化時觸發,獲取textareascrollHeight,再除以oneHeight求整數然后加一就是rows的數量。

踩坑感想:
這樣做是可以實現當內容變多,行數跟着變多的情況的,但是,當內容變少,scrollHeight是不會減少的!所以rows也不會變,一旦被撐大,就再也縮不回去。。。。顯然,這不是我想要的效果。

正確姿勢

猛然回想起ElementUI上就有可根據內容調整高度的組件ElementUI input
然后就去扒源碼看看是怎么實現的,結果都已經封裝好了,太棒了,直接下載來引用就行了!

餓了么組件的源碼github地址:
https://github.com/ElemeFE/element/blob/dev/packages/input/src/calcTextareaHeight.js

下面是引用了ElementUIinput組件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>

摘至:https://www.jianshu.com/p/23c3a6d5dfdf


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM