feat(textarea): 根据内容自适应大小

Signed-off-by: forget skyrim <11513667+forget-skyrim@user.noreply.gitee.com>
This commit is contained in:
forget skyrim 2022-12-07 01:14:38 +00:00 committed by Gitee
parent 38b2941990
commit e0f8a4167a
No known key found for this signature in database
GPG Key ID: 173E9B9CA92EEF8F
2 changed files with 20 additions and 1 deletions

View File

@ -18,6 +18,8 @@
padding: 6px 10px;
resize: vertical;
position: relative;
transition: none;
-webkit-transition: none;
}
.layui-textarea-wrapper {

View File

@ -6,7 +6,8 @@ export default {
<script setup lang="ts">
import { LayIcon } from "@layui/icons-vue";
import { computed, ref } from "vue";
import { computed, ref, watch } from "vue";
import {isObject } from "@vueuse/shared"
import "./index.less";
export interface TextareaProps {
@ -17,6 +18,7 @@ export interface TextareaProps {
showCount?: boolean;
allowClear?: boolean;
maxlength?: number;
autosize?: boolean | { minHeight: number, maxHeight: number };
}
const props = defineProps<TextareaProps>();
@ -31,6 +33,7 @@ interface TextareaEmits {
}
const emit = defineEmits<TextareaEmits>();
const textareaRef = ref<HTMLTextAreaElement | null>(null);
const composing = ref(false);
const onInput = function (event: Event) {
@ -78,11 +81,25 @@ const wordCount = computed(() => {
}
return count;
});
watch([() => props.modelValue, textareaRef], () => {
if (!textareaRef.value || !props.autosize) return;
const height: number = textareaRef.value?.scrollHeight + 2; //
if (isObject(props.autosize)) {
const { minHeight, maxHeight } = props.autosize;
if (height < minHeight || height > maxHeight) return;
}
textareaRef.value!.style.height = '1px'
textareaRef.value!.style.height = `${textareaRef.value?.scrollHeight + 2}px`
}, {
immediate: true,
})
</script>
<template>
<div class="layui-textarea-wrapper">
<textarea
ref="textareaRef"
class="layui-textarea"
:value="modelValue"
:placeholder="placeholder"