vue封装一个自适应高度的输入框组件

html 自带的 input 标签和 textarea 标签高度都无法自适应,当然我们还有一个方法就是给 div 元素添加 contenteditable 属性。

2940 热度
980 浏览

实现一个具有双向绑定功能的自适应高度的输入框组件

1、首先写入 template 代码,

vue 复制代码
<template>
  <div class="auto-height-wrap">
    <textarea
      ref="textarea"
      class="now-textarea"
      :value="modelValue"
      :placeholder="placeholder"
      :style="[styleObject, { height: textareaHeight + 'px' }]"
      rows="1"
      @input="handleInput"
      @keydown="handleKeyDown"
    ></textarea>
  </div>
</template>

<script>
export default {
  name: "AutoHeightInput",
  props: {
    modelValue: {
      type: [String, Number],
      default: ""
    },
    placeholder: {
      type: String,
      default: ""
    },
    styleObject: {
      type: Object,
      default: () => ({})
    },
    minHeight: {
      type: Number,
      default: 20
    },
    maxHeight: {
      type: Number,
      default: 400
    }
  },
  data() {
    return {
      textareaHeight: this.minHeight
    };
  },
  mounted() {
    this.adjustHeight();
  },
  watch: {
    modelValue() {
      // 外部修改时也要调整高度
      this.$nextTick(() => this.adjustHeight());
    }
  },
  methods: {
    handleInput(event) {
      const value = event.target.value;
      this.$emit("update:modelValue", value);
      this.adjustHeight();
    },
    handleKeyDown(event) {
      // 防止 Backspace 导致滚动跳动
      if (event.key === "Backspace" && this.$refs.textarea.scrollTop !== 0) {
        event.stopPropagation();
      }
    },
    adjustHeight() {
      const textarea = this.$refs.textarea;
      if (!textarea) return;

      textarea.style.height = "auto"; // 重置高度以便计算 scrollHeight
      let newHeight = textarea.scrollHeight;

      // 限制最小与最大高度
      newHeight = Math.max(this.minHeight, newHeight);
      newHeight = Math.min(this.maxHeight, newHeight);

      this.textareaHeight = newHeight;
    }
  }
};
</script>

<style lang="less" scoped>
.auto-height-wrap {
  position: relative;
  display: flex;
  width: 100%;
  .now-textarea {
    width: 100%;
    resize: none;
    overflow: hidden;
    padding: 8px;
    border: 1px solid #ccc;
    border-radius: 4px;
    font-size: 14px;
    line-height: 1.5;
    box-sizing: border-box;
    transition: height 0.1s ease;
  }
}
</style>

2、使用方法(Vue 3 语法)

vue 复制代码
<template>
  <div>
    <AutoHeightInput
      v-model="text"
      placeholder="请输入内容..."
      :minHeight="40"
      :maxHeight="300"
    />
  </div>
</template>

<script>
import AutoHeightInput from "./AutoHeightInput.vue";

export default {
  components: { AutoHeightInput },
  data() {
    return {
      text: ""
    };
  }
};
</script>
vue封装一个自适应高度的输入框组件

声明:Web前端小站 - 前端博客 - 王搏的个人博客|版权所有,违者必究|如未注明,均为原创

转载:转载请注明原文链接 - vue封装一个自适应高度的输入框组件

评论 (0)

0/50
暂无评论,快来抢沙发吧~