使用Vue+Textarea实现在文本内容变化时自适应高度

前言

日常记录小技巧,使用Vue+Textarea实现在文本内容变化时自适应高度,还挺好用的。

一、示例代码

1.Vue2.X版本

(1)/src/views/Example/AutoTextarea/index_1.vue

<template>
  <div style="padding: 50px;">
    <el-button size="small" type="primary" plain @click="handleChangeTextareaClick($event)">
      <el-icon :size="18">
        <MagicStick />
      </el-icon>
      <small>点击事件</small>
    </el-button>

    <br /><br />

    <textarea
      class="textarea"
      ref="textareaRef"
      v-model="description"
      :spellcheck="false"
    >
    </textarea>
  </div>
</template>

<script>
export default {
  data: () => ({
    // 文本内容
    description: 'HelloWorld ~!',
  }),
  watch: {
    /**
     * 深度监听文本内容
     */
    description: {
      handler(newVal, oldVal) {
        if (newVal != oldVal) {
          // 文本内容变化
          this.handleChangeTextareaHeight()
        }
      },
      deep: true
    }
  },
  methods: {
    /**
     * 动态改变文本句柄方法
     */
    handleChangeTextareaClick(evt) {
      let len = Math.floor(Math.random() * (500 - 100 + 1) + 100)
      this.description = this.getRandomChineseText(len)
    },

    /**
     * 随机生成 200 - 800 个中文
     */
    getRandomChineseText(len) {
      let res = ''
      for (let i = 0; i < len; i++) {
        var randomUnicode = Math.floor(Math.random() * (40869 - 19968)) + 19968
        res += String.fromCharCode(randomUnicode)
      }
      return res
    },

    /**
     * 动态改变 Textarea 容器高度事件句柄方法
     * Vue.nextTick(() => {}) 将回调函数延迟在下一次DOM更新数据过后进行调用
     */
    async handleChangeTextareaHeight() {
      this.$nextTick(async () => {
        
        const textareaRef = await this.$refs.textareaRef
        console.dir(textareaRef) // 打印元素的所有属性
        console.log('textareaRef.offsetHeight = ' + textareaRef.offsetHeight)
        console.log('textareaRef.scrollHeight = ' + textareaRef.scrollHeight)

        textareaRef.style.height = 'auto' // 先重置元素的高度,此行代码可以试试注释看看打印效果 ~
        textareaRef.style.height = textareaRef.scrollHeight + 'px' // 再设置元素的真实高度,此行代码可以试试注释看看打印效果 ~

        console.log('')
      })
    }
  }
}
</script>

<style>
  .textarea {
    padding: 10px;
    background-color: #f5f7fa;
    border: 1px solid #e4e7ed;
    border-radius: 3px;
    outline: none;
    font-family: emoji;
  }
</style>

2.Vue3.X版本

(1)/src/views/Example/AutoTextarea/index_2.vue

// watch 监听事件
watch(description, (newValue, oldValue) => {
  handleChangeTextareaHeight()
})

// 改变 Textarea 容器高度事件句柄方法
const handleChangeTextareaHeight = () => {
  // ...
}

 二、运行效果

  • 4
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值