Vue列表如何实现滚动到指定位置样式改变效果

2020-06-16 06:41:57易采站长站整理

这个需求大概是这样子:

我做的一个聊天Demo,在搜索框搜索用户,可以滚动到指定的用户。然后成选中状态。

这是目前状态,我搜索南宫仆射 ,想要下面的用户列表直接滚动到南宫仆射并改变CSS样式。

查询之后是这个子:

嗯,我的思路:

在搜索框搜索到用户之后会返回一个用户对象,之后会调用列表的点击事件,改变CSS样式及做一些聊天的逻辑。然后需要获取到列表对应的id值,直接使用

document.getElementById(it).scrollIntoView();

具体实现:

列表:使用vue的v-for指令 ,这里的id值使用的是遍历的索引值,外层是一个自定义滚动条组件。样式也是使用vue指令,一个语法糖。


<GeminiScrollbar
class="my-scroll-bars">
<li v-for="(item,index) in hrs" :id="index"
:key="index"
:class="{ active: currentSession?item.username === currentSession.username:false}"
@click="changeCurrentSession(item)">
<img class="avatar"
:src="item.userface">
<el-badge :is-dot="isDot[user.username+'#'+item.username]">
<p class="name">{{item.name}}</p>
</el-badge>
</li>
</GeminiScrollbar>

搜索框:这里使用带提示的输入框,


<el-autocomplete
v-model="SearchHr" class="input-with-select" popper-append-to-body="false"
style="width: 90%;padding-left: 5%;padding-top: 10px;margin-bottom: 10px"
size="small"
:fetch-suggestions="querySearch"
placeholder="请输入内容"
@select="handleSelect"
>
<el-button slot="append" icon="el-icon-search"
@click="SearchCurrentSession(SearchHr)"></el-button>
</el-autocomplete>

JS代码:请求为get请求的axios封装,hr为查询返回的对象,hrs为所有的列表对象。


SearchCurrentSession() {
this.getRequest("/chat/?name=" + this.SearchHr).then(resp => {
if (resp) {
this.hr = resp;
this.SearchHr = '';
this.changeCurrentSession(this.hr);
let it = 0;
this.hrs.forEach((item, index) => {
if (item.name == this.hr.name) {
it = index;
}
})
document.getElementById(it).scrollIntoView();
// document.getElementsByClassName("active")[0].scrollIntoView();

}
});