组件如下
子组件定义组件
<template>
<div class='abc'
:data-error="error"
:class="{ error: error }">
<textarea
class="paper-textarea"
:placeholder="placeholder"
:rows="rows"
:value="textAreaValue"
:maxlength="maxlength"
@input="getTextAreaValue"
/>
<div class="paper-length-maxlength">
<span>{{ lengthText }}</span> / <span>{{ maxlength }}</span>
</div>
</div>
</template>
<script setup>
import { watch, ref,nextTick } from "vue";
let props = defineProps({
placeholder:'',
maxlength:'',
error: '',
rows:'',
modelValue:''
})
let emit = defineEmits(["update:modelValue"]);
let textAreaValue = ref(props.modelValue);
let lengthText = ref(props.modelValue?.length|| 0);
const getTextAreaValue=(e) =>{
const event = e || window.event;
const target = event.srcElement || event.taget;
emit("update:modelValue", target.value);
}
watch(
() => props.modelValue,
(val) => {
textAreaValue.value = val;
lengthText.value = val.length;
}
);
</script>
<style lang="scss" scoped>
.abc{
width: 100%;
position: relative;
}
.paper-length-maxlength {
position: absolute;
bottom: 10px;
right: 10px;
font-size: 13px;
color: #909499;
}
.paper-textarea {
border: none;
width: 100%;
background: rgba(255, 255, 255, 0.08);
outline: none;
border: none;
color: #fff;
border: 1px solid transparent;
/** 禁止textarea拉伸 */
// resize: none;
&:focus {
border: 1px solid #2b8ce5;
}
&.error {
border: 1px solid #f53f3f;
}
&:after {
content: attr(data-error);
position: absolute;
left: 0;
color: var(--color-error);
font-size: 12px;
width: max-content;
}
/* WebKit, Blink, Edge */
&::-webkit-input-placeholder {
color: #909499;
}
/* Mozilla Firefox 4 to 18 */
&:-moz-placeholder {
color: #909499;
}
/* Mozilla Firefox 19+ */
&::-moz-placeholder {
color: #909499;
}
/* Internet Explorer 10-11 */
&:-ms-input-placeholder {
color: #909499;
}
}
</style>
父组件引入去使用
<Textarea
error=""
placeholder='100字以内'
maxlength='100'
rows='5'
v-model="formModal.Textarea"
>
</Textarea>
以上就是Textarea组件的封装和使用啦!