项目需求:需要从商品列表页diamond中点击某一个商品进入商品详情页productDetail后,从详情页返回到列表页时需保持原来的滚动位置,并使用keep-alive进行组件缓存实现性能优化
1、在路由中设置keepAlive
属性默认为true,避免无法及时识别是否需要缓存
{
path: '/diamond',
name: 'diamond',
component: diamond,
meta: {
keepAlive: true
}
},
2、在App.vue中设置动态设置keepAlive
属性判断是否需要缓存
<div id="app" :class="deviceClass">
<keep-alive :include="['diamond', 'product']">
<router-view v-if="$route.meta.keepAlive"></router-view>
</keep-alive>
<router-view v-if="!$route.meta.keepAlive"></router-view>
</div>
3、当从列表页离开时,如果即将去往的页面不是详情页,则keepAlive = false即不需要缓存列表页,否则keepAlive = true
diamond页面
beforeRouteLeave (to, from, next) {
// 如果进入详情页则缓存当前列表页,否则不缓存当前列表页
if (to.name !== 'productDetail') {
from.meta.keepAlive = false
} else {
from.meta.keepAlive = true
}
next((vm) => {})
}
4、在点击某一个商品进入详情页时,缓存滚动距离diamondScrollTop
diamond页面
itemClick (ind) {
// 选中列表项
const item = this.tableData.find(({ key }) => key)
if (item) {
item.key = false
}
this.tableData[ind].key = true
this.rowClick(this.tableData[ind])
// 缓存滚动距离diamondScrollTop
const listBox = document.getElementById('list-box')
this.utils.setSessionStorage('diamondScrollTop', listBox.scrollTop)
this.$forceUpdate()
},
rowClick (row, column, event) {
// 去详情
this.$router.push(
'productDetail?id=' + (row.pid || row.id) + '&type=1'
)
},
5、在activated里需要设置滚动到上次滚动的距离
diamond页面
activated () {
// 组件激活时恢复滚动位置
const listBox = document.getElementById('list-box')
if (listBox) {
this.utils.getSessionStorage('diamondScrollTop').then((scrollTop) => {
listBox.scrollTop = scrollTop
})
}
},
6、在created中设置初始滚动距离为0 --- 当从首页进入列表页时需要从顶部开始
diamond页面
created () {
...
this.$nextTick(() => this.getList(true, false))
// 设置初始滚动值diamondScrollTop为0
this.utils.setSessionStorage('diamondScrollTop', 0)
},
注意:
1、使用id选择器获取滚动容器id="list-box"
<div class="list-box" id="list-box" @scroll="handleScroll">
<div v-if="tableData.length">
<div
class="list-item flex"
v-for="(item, index) in tableData"
:key="index"
@click="itemClick(index)"
>
<div class="true-icon" v-show="selectMode && item.key">
<icon
:isUrl="'diamond_subscript_selected_icon'"
:isStyle="'width:37.44rem;height:37.44rem'"
></icon>
</div>
...
</div>
</div>
</div>
const listBox = document.getElementById('list-box')
2、列表容器listBox必须有滚动条才能设置listBox.scrollTop = scrollTop
.list-box {
padding: 0 15rem;
flex: 1;
overflow-y: auto;
min-height: 460rem;
.list-item {
width: 100%;
background: #FFF;
border: 1px solid #B0A69A;
opacity: 1;
border-radius: 4rem;
padding: 13rem 20rem 11rem 0;
margin-bottom: 4rem;
}
}
标签:缓存,滚动,vue,alive,列表,滚动条,diamond,listBox,keepAlive
From: https://blog.csdn.net/m0_58190742/article/details/144933752