el-textarea v-show 下 autosize出现滚动条
项目场景:vue3+element-plus,页面中有三个tab切换,每个tab切换下都有input输入框,其中type类型为textarea时要求autosize为true,可以根据输入内容自动撑开个输入框高度;三个tab使用v-show切换显示隐藏。
问题描述
实际测试过程中发现,当切换tab时,input输入类型为textarea的输入框出现了滚动条,如下图:
解决方案:
这里使用el-textarea的resizeTextarea
方法,监听当前tab变化重新执行resizeTextarea,代码片段如下:
1、给循环的el-input 动态生成ref
<el-input
v-model="scope.row[key]"
:ref="
el =>
setRefItem({
el,
key,
index: scope.$index,
subKey,
type: column.options?.inputType || column.type,
})
"
:type="column.options?.inputType || column.type"
:autosize="true"
resize="none"
...
// 获取所有textarea的ref 放入inputRefMap中
const inputRefMap = ref({});
const setRefItem = ({ el, key, index, subIndex, subKey, type }) => {
if (el && type === 'textarea') {
let name =
subIndex === 0 || subIndex
? `input_ref_${key}_${index}_${subKey}_${subIndex}`
: `input_ref_${key}_${index}`;
inputRefMap.value[name] = el;
}
};
2、监听当前选中tab(currentTabRadio.value) 同时重新执行resizeTextarea方法
let timer = null;
const resizeTextarea = currentTabRadio => {
nextTick(() => {
timer && clearTimeout(timer);
timer = setTimeout(() => {
let inputRefObj = null;
if (currentTabRadio === 'outcomeIndicators') {
inputRefObj = outcomeRef.value.inputRefMap;
} else if (currentTabRadio === 'majorProjects') {
inputRefObj = majorprojectRef.value.inputRefMap;
} else if (currentTabRadio === 'continuousImprovements') {
inputRefObj = continuousImprovementsRef.value.inputRefMap;
}
if (inputRefObj && Object.keys(inputRefObj).length > 0) {
for (let key in inputRefObj) {
const el = inputRefObj[key];
el && el.resizeTextarea();
}
}
}, 50);
});
};
watch(
[() => currentTabRadio.value],
([currentTabRadio]) => {
resizeTextarea(currentTabRadio);
},
{
immediate: true,
}
);
注意:加了settimeout为50ms的延迟是因为不加的话发现高度在计算时会出现高于本身内容高度的情况,如下图:
3、因为缩小屏幕时高度不变导致textarea出现滚动条,所以就加个监听页面滚动的方法
import debounce from 'lodash/debounce';
...
const debounceResizeTextarea = debounce(() => {
resizeTextarea(currentTabRadio.value);
}, 100);
onMounted(() => {
window.addEventListener('resize', debounceResizeTextarea);
});
onUnmounted(() => {
window.removeEventListener('resize', debounceResizeTextarea);
});
4、切换时因为加了nextick 和 延迟 导致会出现快速的先出现滚动条然后又消失的情况,不利于用户体验,因此加了css样式去屏蔽掉:
.el-textarea__inner {
overflow: hidden !important;
}