【问题标题】:Question for auto-resizing Textarea using VueJS使用 VueJS 自动调整 Textarea 大小的问题
【发布时间】:2022-01-22 06:18:35
【问题描述】:

我正在尝试让文本区域在文本值更改时自动调整其高度:

<textarea ref="textarea" v-model="message"> </textarea>

我使用了一个监视器来监视与文本区域相关的组件变量“消息”。每当消息发生变化时,都会触发一个函数来调整文本区域的高度:

watch: {
  message: function(){
    this.$refs.textarea.style.height="auto";
    this.$refs.textarea.style.height = this.$refs.textarea.scrollHeight + 'px';
  },
}

如果我在框内手动输入,该代码运行良好。但是,如果我使用方法来更新 textarea 变量“message”,则框的大小不会正确更新。

为了更清楚,我创建了一个小提琴项目:https://jsfiddle.net/ttl66046/9nycdq60/4/ 在这里写代码:https://codepen.io/ttl66046/pen/eYGqJWm

文本框下方有两个按钮。每个按钮都与一个短文本相关联。理想情况下,文本框的高度应根据您单击的按钮(您选择的文本)进行更新。这里有什么问题?

【问题讨论】:

    标签: javascript html vue.js vue-component textarea


    【解决方案1】:

    观察者的效果直到下一个渲染周期才被渲染。 message watcher 设置height 两次(一次设置为auto,然后立即scrollHeight 覆盖它),但组件不会在每次设置之间重新渲染。

    关键是在下一个渲染周期中用$nextTick() callback更新height

    export default {
      watch: {
        message: function() {
          this.$refs.textarea.style.height = "auto";
                   ?
          this.$nextTick(() => {
            this.$refs.textarea.style.height = this.$refs.textarea.scrollHeight + 'px';
          })
        }
      }
    }
    

    updated codepen

    【讨论】:

    • 非常感谢。你刚刚救了我的命!我在这里看到了问题。所以基本上,我的代码的问题是“this.$refs.textarea.scrollHeight”还没有完成渲染。 $nextTick() 只是等待让观察者中的函数在下一个循环之后等待(或让文本框完成渲染)。
    【解决方案2】:

    在css中添加以下代码:

    textarea {
        width:200px;
        resize:none;
      }

    【讨论】:

    • 它不工作。文本区域的高度仍然没有正确改变。
    【解决方案3】:

    如果您想在更改 TEXT 时使用“+”行和“-”行,请使用 Vue3(Composition API for me):

                <textarea
                   id="newComm"
                   class="form-control"
                   name="comment"
                   placeholder="Some text you want"
                   cols="30"
                   :rows="rowsHeight"
                   wrap="soft"
                   v-model.trim="newCommText"
                   @input="changeRows"
                   :style="'resize: none; overflow: hidden; line-height: '+lineHeight+'px;'"
            ></textarea>
    
        setup() {
        /*--------your code here--------*/
    
        const newCommText = ref(null)
        const rowsHeightStart = ref(5)
        const rowsHeight = ref(rowsHeightStart.value)
        const lineHeight = ref(25)
        function changeRows (event) {
            rowsHeight.value = event.target.value.split("\n").length > rowsHeightStart.value ? event.target.value.split("\n").length : rowsHeightStart.value
        }
    
        return {
             rowsHeight, lineHeight, newCommText,
            changeRows
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-25
      • 2013-06-21
      • 1970-01-01
      • 1970-01-01
      • 2021-11-26
      • 2019-06-24
      • 1970-01-01
      • 2011-07-14
      相关资源
      最近更新 更多