1、最近在做移动端的首页时有列表点击进去详情页,再返回时列表页的浏览位置不变的功能。如下:
2、上代码
在app.vue中:
<template>
<div id="app">
<keep-alive>
<router-view v-if="$route.meta.keepAlive"></router-view>
</keep-alive>
<router-view v-if="!$route.meta.keepAlive"></router-view>
</div>
</template>
在路由文件中:
const routes = [
...homeRouter,
]
let HomeRouter = [{
path: "/home",
name: "Home",
component: () =>
import ('@/views/home/index.vue'),
meta: {
title: '首页',
keepAlive: true
}
},
]
export default HomeRouter
在js中:
<script>
export default {
data() {
return {
scrollTops:"",
};
},
activated () { // 路由跳转回来滚动到离开时的位置
this.$nextTick(() => {
this.$refs.container.scrollTop = this.scrollTops;
})
},
methods: {
scrollEvent(e){ // 监听滚动距离
this.scrollTops = e.target.scrollTop;
},
},
},
</script>
html中:
<template>
<div class="container" @scroll="scrollEvent" ref="container">
<div class="topCon">
</div>
</div>
</template>
<style lang="scss" scoped>
.container {
background: #f2f2f2;
height: 100%; // 这个很关键
overflow: auto;//这个很关键
}
</style>
在最后提示一下:监听事件scrollEvent触发,一定要加上以上css属性哦!
因篇幅问题不能全部显示,请点此查看更多更全内容