vue 列表刷新后置
时间: 2023-06-29 07:20:25 浏览: 45
如果您想在 Vue 列表刷新后将滚动位置保持在原来的位置,可以使用以下步骤:
1. 在 Vue 列表组件的父组件中,添加一个 `ref` 属性来引用列表组件,例如:
```html
<template>
<div ref="listContainer">
<list-component :items="items" />
</div>
</template>
```
2. 在列表组件中,使用 `mounted` 钩子函数来获取列表容器的高度和滚动位置,并将其作为 `data` 中的变量保存起来,例如:
```javascript
export default {
mounted() {
this.listContainer = this.$parent.$refs.listContainer;
this.listHeight = this.listContainer.offsetHeight;
this.scrollTop = this.listContainer.scrollTop;
},
data() {
return {
listContainer: null,
listHeight: 0,
scrollTop: 0,
};
},
};
```
3. 在列表组件的更新钩子函数 `updated` 中,使用保存的高度和滚动位置来设置列表容器的新高度和滚动位置,例如:
```javascript
export default {
updated() {
const newHeight = this.listContainer.offsetHeight;
const newScrollTop = this.scrollTop + (newHeight - this.listHeight);
this.listHeight = newHeight;
this.listContainer.scrollTop = newScrollTop;
},
// ...
};
```
这样,每当列表组件更新时,它会自动计算出新的高度和滚动位置,并将列表容器滚动到正确的位置,从而保持滚动位置的连续性。