我试图让文本区域在文本值发生变化时自动调整其高度:
<textarea ref="textarea" v-model="message"> </textarea>
我使用了一个观察者来监视与文本区域关联的组件变量“message”。每当消息发生变化时,就会触发一个函数来调整文本区域的高度:
watch: {
message: function(){
this.$refs.textarea.style.height="auto";
this.$refs.textarea.style.height = this.$refs.textarea.scrollHeight + 'px';
},
}
如果我在框中手动输入,代码效果很好。但是,如果我使用方法来更新文本区域变量“消息”,则框的大小不会正确更新。
为了更清楚地说明,我创建了一个小提琴项目:https://jsfiddle.net/ttl66046/9nycdq60/4/ 代码笔在这里:https://codepen.io/ttl66046/pen/eYGqJWm
文本框下方有两个按钮。每个按钮都与一个短文本相关联。理想情况下,文本框的高度应根据您单击的按钮(您选择的文本)进行更新。这是什么问题?
观察者的效果直到下一个渲染周期才会渲染。
message
观察者将 height
设置两次(一次设置为 auto
,然后 立即 用 scrollHeight
覆盖它),但组件不会在每次设置之间重新渲染。
关键是在下一个渲染周期中使用
height
回调更新$nextTick()
:
export default {
watch: {
message: function() {
this.$refs.textarea.style.height = "auto";
👇
this.$nextTick(() => {
this.$refs.textarea.style.height = this.$refs.textarea.scrollHeight + 'px';
})
}
}
}
在css中添加以下代码:
textarea {
width:200px;
resize:none;
}
如果您想在更改文本时使用“+”行和“-”行,请使用 Vue3(对我来说是 Composition API):
<textarea
id="newComm"
class="form-control"
name="comment"
placeholder="Some text you want"
cols="30"
:rows="rowsHeight"
wrap="soft"
v-model.trim="newCommText"
@input="changeRows"
:style="'resize: none; overflow: hidden; line-height: '+lineHeight+'px;'"
></textarea>
setup() {
/*--------your code here--------*/
const newCommText = ref(null)
const rowsHeightStart = ref(5)
const rowsHeight = ref(rowsHeightStart.value)
const lineHeight = ref(25)
function changeRows (event) {
rowsHeight.value = event.target.value.split("\n").length > rowsHeightStart.value ? event.target.value.split("\n").length : rowsHeightStart.value
}
return {
rowsHeight, lineHeight, newCommText,
changeRows
}
您可以使用
<script setup>
语法在 VueJS 3 中创建自动调整大小的文本区域:
创建一个Vue组件(例如ChatMessage.vue):
<template>
<div class="chat-message">
<textarea
v-model="message"
@input="adjustTextarea"
ref="textarea"
class="autoresize"
placeholder="Type a message..."
></textarea>
</div>
</template>
<script setup>
import { ref } from 'vue';
const message = ref('');
const textarea = ref(null);
const adjustTextarea = () => {
textarea.value.style.height = 'auto';
textarea.value.style.height = `${textarea.value.scrollHeight}px`;
};
</script>
<style scoped>
.autoresize {
resize: none;
overflow: hidden;
min-height: 40px;
max-height: 120px;
}
</style>
您可以在 Vue 应用程序中使用此组件,如下所示:
<template>
<div id="app">
<ChatMessage />
</div>
</template>
<script>
import ChatMessage from "./ChatMessage.vue";
export default {
components: {
ChatMessage
}
};
</script>