如何实现vue的textarea高度自适应?

使用 Vue 实现一个输入框,输入框有一个默认高度和一个最大高度,当超过默认高度但未及最大高度时,想让输入框自动增高。这该如何实现?

经过思考以及查阅资料,它的实现思路就是在输入内容时,检测输入框的 scrollHeight 值,然后再动态地设置为 height。实现的方法分为以下两种:

一、封装成组件

单独写一个 AutoHeightText.vue 文件。然后在里面实现对 textarea 的监听。代码如下:

<template>
  <textarea v-model="text" ref="textarea" :style="{height: textareaHeight}" :placeholder="placeholder" @focus="resize"></textarea>
</template>

<script>
export default {
  props: {
    defaultHeight: {
      typeString,
      default'auto',
    },
    placeholder: {
      typeString,
      default'请输入...',
    },
    value: {
      typeString,
      default'',
    },
  },

  data() {
    return {
      textthis.value,
      textareaHeightthis.defaultHeight,
    }
  },

  watch: {
    text(newValue) {
      this.$emit('input', newValue)
      this.$nextTick(this.resize)
    },
  },

  methods: {
    resize() {
      this.textareaHeight = this.defaultHeight
      this.$nextTick(() => {
        this.textareaHeight = `${this.$refs.textarea.scrollHeight}px`
      })
    },
  },
}
</script>

使用示例如下:

<auto-height-text :class="$style.textarea" defaultHeight="40px" placeholder="添加评论..." v-model="item.newComment" />

<style lang="sCSS" scoped>
.textarea {
  width100%;
  height40px;
  max-height100px;
  border0.5px solid #666666;
  border-radius4px;
  padding8px 14px;
  font-size14px;
  line-height24px;
  color#000000;
  outline: none;
  resize: none;
  box-sizing: border-box;
  overflow: hidden;
}
</style>

有同学可能会想,为什么要在 focus 事件中来执行 resize,然后又在 watch 中监听,发生改变再执行 resize。直接使用 @input@change 监听,这样难道不是更方便吗?这里我们需要注意 $emit 的时机以及不同的事件触发 resize 的时机,有兴趣的同学可以自己试试。

二、封装成一个指令

这里只简单介绍注册局部指令,当然如果使用的多,也可以注册一个全局指令。

<script>
directives: {
  autoHeight: {
    update(el, binding) {
      const { value } = binding
      if (value && typeof value === 'number') {
        el.style.height = `${value}px`
      } else {
        el.style.height = 'auto'
      }
    },
    componentUpdated(el) {
      el.style.height = `${el.scrollHeight}px`
    },
  },
},
</script>

使用示例如下:

<textarea :class="$style.textarea" v-autoHeight="40" v-model="testContent" placeholder="请输入测试的内容"></textarea>

<style lang="scss" scoped>
.textarea {
  width100%;
  max-height100px;
  border0.5px solid #666666;
  border-radius4px;
  padding8px 14px;
  font-size14px;
  line-height24px;
  color#000000;
  outline: none;
  resize: none;
  box-sizing: border-box;
  overflow: hidden;
}
</style>

不足之处,请指正🤟🤟🤟~~~

参考链接

  • https://Github.com/devstark-com/vue-textarea-autosize
  • https://cn.vuejs.org/v2/guide/custom-directive.html

如何实现vue的textarea高度自适应?



原文始发于微信公众号(前端学习总结):如何实现vue的textarea高度自适应?

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由半码博客整理,本文链接:https://www.bmabk.com/index.php/post/83214.html

(0)

相关推荐

发表回复

登录后才能评论
半码博客——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!