日常记录小技巧,Vue使用Textarea实现在文本内容变化时自适应高度。
<template>
<div style="padding: 50px;">
<el-button size="small" type="primary" plain @click="handleChangeTextareaClick($event)">
<el-icon :size="18">
<MagicStick />
</el-icon>
<small>点击事件</small>
</el-button>
<br /><br />
<textarea
class="textarea"
ref="textareaRef"
v-model="description"
:spellcheck="false"
>
</textarea>
</div>
</template>
<script>
export default {
data: () => ({
// 文本内容
description: 'HelloWorld ~!',
}),
watch: {
/**
* 深度监听文本内容
*/
description: {
handler(newVal, oldVal) {
if (newVal != oldVal) {
// 文本内容变化
this.handleChangeTextareaHeight()
}
},
deep: true
}
},
methods: {
/**
* 动态改变文本句柄方法
*/
handleChangeTextareaClick(evt) {
let len = Math.floor(Math.random() * (500 - 100 + 1) + 100)
this.description = this.getRandomChineseText(len)
},
/**
* 随机生成 200 - 800 个中文
*/
getRandomChineseText(len) {
let res = ''
for (let i = 0; i < len; i++) {
var randomUnicode = Math.floor(Math.random() * (40869 - 19968)) + 19968
res += String.fromCharCode(randomUnicode)
}
return res
},
/**
* 动态改变 Textarea 文本高度
* Vue.nextTick(() => {}) 将回调函数延迟在下一次DOM更新数据过后进行调用
*/
async handleChangeTextareaHeight() {
this.$nextTick(async () => {
const textareaRef = await this.$refs.textareaRef
console.dir(textareaRef) // 打印元素的所有属性
console.log('textareaRef.offsetHeight = ' + textareaRef.offsetHeight)
console.log('textareaRef.scrollHeight = ' + textareaRef.scrollHeight)
textareaRef.style.height = 'auto' // 先重置元素的高度,此行代码可以试试注释看看打印效果 ~
textareaRef.style.height = textareaRef.scrollHeight + 'px' // 再设置元素的真实高度,此行代码可以试试注释看看打印效果 ~
console.log('')
})
}
}
}
</script>
<style>
.textarea {
padding: 10px;
background-color: #f5f7fa;
border: 1px solid #e4e7ed;
border-radius: 3px;
outline: none;
font-family: emoji;
}
</style>
效果如下 ~
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/151149.html