html 自带的 input 标签和 textarea 标签高度都无法自适应,当然我们还有一个方法就是给 div 元素添加 contenteditable 属性。
实现一个具有双向绑定功能的自适应高度的输入框组件
1、首先写入 template 代码,
<template>
<div class="auto-height-wrap">
<textarea class="now-textarea" :value="value" cols="20" rows="1" :style="styleObject" :placeholder="placeholder" @input="handleChange" @keydown="handleKeyDown" ref="textarea"></textarea>
</div>
</template>
2、script 代码
<script>
export default {
props: {
// v-model 绑定的值
value: [String, Number],
placeholder: {
type: String,
default: ''
},
styleObject: {
type: Object,
default: _ => { }
}
},
mounted() {
this.setHeight();
},
methods: {
handleChange(event) {
this.$emit('input', event.target.value);
this.setHeight();
},
handleKeyDown(event) {
if (event.key === 'Backspace' && this.$refs.textarea.scrollTop !== 0) {
event.stopPropagation();
}
},
setHeight() {
this.$refs.textarea.style.height = 'auto';
let auto_height = this.$refs.textarea.scrollHeight
this.$refs.textarea.style.height = `${auto_height}px`;
}
}
};
</script>
3、样式代码,我这里使用的是 less
<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;
min-height: 20px;
box-sizing: border-box;
}
}
</style>
4、使用组件
先引入
import AutoHeightInput from "./autoHeightInput.vue";
双向绑定
<AutoHeightInput v-model="text" />