优化textarea组件

master
chenjiajian 2023-04-14 11:53:52 +08:00
parent f99f1b34f3
commit 88b7a741d9
1 changed files with 24 additions and 5 deletions

View File

@ -18,6 +18,8 @@ class TextArea extends Component {
readOnly: false, readOnly: false,
disabled: false, disabled: false,
autosize: false, autosize: false,
maxheight: null,
minheight: null,
maxlength: null, maxlength: null,
minlength: null, minlength: null,
'show-limit': false, 'show-limit': false,
@ -157,11 +159,24 @@ class TextArea extends Component {
onInput(e) { onInput(e) {
this.value = e.target.value this.value = e.target.value
if (this.autosize) { if (this.autosize) {
nextTick(() => { nextTick(() => this.adjustTextareaSize())
this.$refs.textarea.style.height = 'auto' }
let height = this.$refs.textarea.scrollHeight + 'px' }
this.$refs.textarea.style.height = height adjustTextareaSize() {
}) let { maxheight, minheight } = this
const input = this.$refs.textarea
input.style.height = 'auto'
let height = input.scrollHeight
if (minheight && !Number.isNaN(+minheight)) {
height = Math.max(minheight, height)
}
if (maxheight && !Number.isNaN(+maxheight)) {
input.style.overflow = height > maxheight ? 'auto' : 'hidden'
height = Math.min(maxheight, height)
}
if (input.style.height !== height) {
input.style.height = height + 'px'
} }
} }
onKeydown(ev) { onKeydown(ev) {
@ -223,6 +238,10 @@ class TextArea extends Component {
// 火狐浏览器需要手动focus()才能聚焦成功 // 火狐浏览器需要手动focus()才能聚焦成功
nextTick(_ => this.$refs.textarea.focus()) nextTick(_ => this.$refs.textarea.focus())
} }
if (this.autosize) {
this.minheight = this.minheight || this.offsetHeight - 2
this.adjustTextareaSize()
}
} }
} }