效果图:
代码如下:
data () {return {description: '',//双向数据绑定初始定义}},watch: {"description" (newVal, oldVal) {if (newVal === oldVal) {return;}this.description = newVal;this.forceUpdateKey += 1;this.changeTextareaHeight();//调用事件}},methods:{changeTextareaHeight () {//控制高度let _this = this;this.$nextTick(() => {let textarea = _this.$refs.textareaRef;//这里ref名字一致。var scrollHeight = textarea.scrollHeight; // 控件所有的高度,包含滚动的那部分(不可见也会有高度)var height = textarea.offsetHeight; // 屏幕上显示的高度if (height <= scrollHeight) {textarea.style.height = 'auto'; // 恢复默认值,这个作用就是根据内容自适应textarea高度textarea.style.height = textarea.scrollHeight + 'px'; // 拿到最新的高度改变textarea的高度}})},}