
element-plus滚动条el-scrollbar始终保持在底部--(已解决)
最近搞这个搞了4,5个小时,简单的可以做到了,但是如果要在数据加载后再执行要放update钩子函数里还要nextTick(没人带自学好痛苦),
简单的代码
<script setup lang="ts">
import { dayjs } from 'element-plus';
import { ElScrollbar as ElScrollbarType } from 'element-plus';
import {nextTick, ref} from "vue";
const innerRef = ref<HTMLDivElement>()
const scrollbarRef = ref<InstanceType<typeof ElScrollbarType>>()
const items = ref<string[]>([])
const handleClick = () => {
items.value.push(dayjs().format('YYYY-MM-DD HH:mm:ss SSS'));
nextTick(() => {
if (innerRef.value!.clientHeight > 200) {
scrollbarRef.value!.setScrollTop(innerRef.value!.clientHeight)
}
})
}
</script>
<template>
<el-scrollbar height="200px" ref="scrollbarRef" always>
<div ref="innerRef">
<p v-for="item in items" :key="item" class="scrollbar-demo-item">{{ item }}</p>
</div>
</el-scrollbar>
<el-button type="primary" @click="handleClick">add</el-button>
</template>
<style scoped>
.scrollbar-demo-item {
display: flex;
align-items: center;
justify-content: center;
height: 50px;
margin: 10px;
text-align: center;
border-radius: 4px;
background: #ecf5ff;
color: #409eff;
}
</style>
我未实现的
//todo 自动滚到底方法
const scrollbarRef = ref(null);
const innerRef = ref(null);
import { ElScrollbar } from 'element-plus';
const scrollToBottom = () => {
console.log("开始");
nextTick(() => {
if (this.innerRef.value.clientHeight > 200) {
this.scrollbarRef.value.setScrollTop(this.innerRef.value.clientHeight)
}
})
}
已实现---
无法实现原因
修正scrollToBottom方法中的this引用问题:在Vue 3的<script setup>语法中,this不再指向组件实例。你需要使用ref来引用DOM元素。
确保在AI回答后调用scrollToBottom方法:在sendChatMsg方法中,AI回答后调用scrollToBottom。
完整代码
const scrollbarRef = ref(null);
const innerRef = ref(null);
const scrollToBottom = () => {
nextTick(() => {
if (innerRef.value.clientHeight > 200) {
scrollbarRef.value.setScrollTop(innerRef.value.scrollHeight);
}
});
}
<el-scrollbar always height="400px"
style="width: 100%;"
ref="scrollbarRef">
<div ref="innerRef" >
<el-row style="display: flex;align-items: center;justify-content: space-between;width: 100%;padding-right: 15px"
v-for="(item, index) in chatData" :key="item.id"
class="row-ai" >
<el-avatar class="avatar"
:style="item.role === 'user'?null:'visibility:hidden'"
:src="userInfoStore.info.userPic?userInfoStore.info.userPic:avatar
"/>
<span
class="scrollbar-demo-item2"
:style="[{height: 30+countLines(item.text)*35+'px'}
,{background: item.role ==='user'?'linear-gradient(to right, #89f7fe 0%,#66a6ff 100%)':null},
{color: item.role ==='user'?'#fff':null}]">
{{postToAi&& index === chatData.length - 1 ?displayedResponse:item.text}}
</span>
<el-avatar class="avatar"
:src="AiAvatar"
:style="item.role === 'assistant'?null:'visibility:hidden'"
/>
</el-row>
</div>
</el-scrollbar>
本文是原创文章,采用 CC BY-NC-ND 4.0 协议,完整转载请注明来自 程序员小徐
评论
匿名评论
隐私政策
你无需删除空行,直接评论以获取最佳展示效果