vue缓存组件记录滚动位置

写业务逻辑的时候 经常遇到列表页进入详情页的场景,这时候一般产品经理就会要求返回的时候回到原来的滚动的位置。
这个需求也写过很多次了,在此分享一下。

keepAlive

要想记录滚动位置 先需要缓存该组件 这里用到了keepAlive组件

App.vue 组件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<template>
<div id=app >
<keep-alive :include="componentArray">
<router-view v-if="$route.meta.keepAlive"></router-view>
</keep-alive>
<router-view v-if="!$route.meta.keepAlive"></router-view>
</div>
</template>

<script>
import { mapGetters, mapState } from 'vuex'
export default {
data() {
return {
}
},
computed: {
...mapState({
componentArray: state => state.aliveComponent.name})
}
}
</script>

这里我把需要缓存的组件的name放在了vuex里,实现动态缓存

Store.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
const aliveComponent = {
state: {
name: [],
},

mutations: {
addAliveComponent: (state, name) => {
if (state.name.indexOf(name) < 0 ) {
state.name.push(name);
}
},

delAliveComponent: (state, name) => {
let ind = state.name.indexOf(name);
if (ind >= 0) state.name.splice(ind, 1);
}
}
}

export default aliveComponent;

要注意的是router.js 需要缓存的组件meta需要设置keepAlive=true

1
{   path: '/orderSearch',component:OrderSearch, meta: {title: '',keepAlive:true}}

目标缓存组件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
<template>
<div class="orderSearch" @scroll="scroll" ref="orderSearch">

</div>
</template>
<script>
import {mapMutations} from 'vuex';
export default {
name:"orderSearch",
data() {
return {
scrollTop:'',
}
},
computed: {

},
created(){

},
mounted(){
this.addAliveComponent('orderSearch');//添加缓存 值为上面的name

},
activated(){
this.$refs.orderSearch.scrollTop = this.scrollTop;//keepAlive组件对应的activated钩子函数,滚动到记录的位置
},
beforeRouteLeave(to,from,next){
if(to.path!="/xxx"){//根据跳转的页面来实现动态缓存页面
this.delAliveComponent("orderSearch");
}
next();
},
methods:{
scroll(e){
this.scrollTop = this.$refs.orderSearch.scrollTop//记录滚动位置
},
...mapMutations([ 'addAliveComponent', 'delAliveComponent']),//注册vuex里的方法
}
}
</script>
0%