Vue 封装一个自动高度的输入框组件


实现高度自适应输入框组件

template
<template>
    <textarea class="default-textarea" :style="styleObject" ref="textarea" v-model="text" :placeholder="placeholder" @input="handleChange" />
</template>
script 可传入样式数据
<script>
export default {
    props: {
        // v-model 绑定的值
        value: [String, Number],
        // 
        placeholder: {
            type: String,
            default: ''
        },
        styleObject: {
            type: Object,
            default: _ => {}
        }
    },
    data() {
        return {
            text: ''
        };
    },
    created() {
        this.text = this.value
    },
    watch: {
        value(newVal) {
            this.text = newVal
        }
    },
    methods: {
        handleChange(event) {
            this.text = event.target.value;
            this.$emit('input', this.text)
            let textarea = this.$refs.textarea;
            textarea.style.height = 'auto';
            textarea.style.height = `${textarea.scrollHeight}px`;
        }
    }
};
</script>


style
<style lang="less" scoped>
.default-textarea {
    width: 100%;
    min-height: 20px;
    border: 0;
    resize: none;
    min-height: 20px;
}
</style>

109

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

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

评论
孙瑞杰生日