n-tab-pane 切换保持位置
时间: 2023-08-13 19:26:06 浏览: 43
`n-tab-pane` 是基于 `ElementUI` 组件库开发的,用于实现选项卡的组件。在使用 `n-tab-pane` 组件时,如果想要在切换选项卡时保持原来的位置,可以通过以下步骤实现:
1. 在 `n-tab-pane` 组件上添加 `name` 属性,并绑定一个变量,例如:
```
<n-tab-pane name="tab1">
```
2. 在组件的 `mounted` 生命周期中,读取并记录当前选项卡的位置,例如:
```
mounted() {
// 读取当前选项卡的位置
const position = sessionStorage.getItem('tab1Position');
// 如果有位置记录,则滚动到相应位置
if (position) {
this.$refs.tab1.$el.scrollTop = position;
}
}
```
3. 在组件的 `activated` 生命周期中,重新设置当前选项卡的位置,例如:
```
activated() {
// 读取之前记录的位置
const position = sessionStorage.getItem('tab1Position');
// 如果有位置记录,则滚动到相应位置
if (position) {
this.$refs.tab1.$el.scrollTop = position;
}
}
```
4. 在组件的 `beforeRouteLeave` 生命周期中,记录当前选项卡的位置,例如:
```
beforeRouteLeave(to, from, next) {
// 记录当前选项卡的位置
sessionStorage.setItem('tab1Position', this.$refs.tab1.$el.scrollTop);
next();
}
```
通过以上步骤,就可以实现 `n-tab-pane` 切换时保持原来位置的功能了。需要注意的是,以上代码中的 `tab1` 都需要根据实际情况进行修改。