在开发中经常有从列表跳到详情页,然后返回详情页的时候需要缓存列表页的原来数据以及滚动位置,这个时候就需要保存状态,要缓存状态。
概括来讲:
-
列表页面 —— 进入详情页 —— 后退到列表页(缓存列表页的原来数据以及滚动位置)
-
重新进入列表页面,获取最新的数据
如何使用
1、创建router实例的时候加上scrollBehavior方法
const createRouter = () => new Router({
routes: constantRoutes,
scrollBehavior(to, from, savedPosition) {
if (savedPosition) {
return savedPosition
} else {
return {
x: 0,
y: 0
}
}
}
})
2、在store的app子模块里加入需要缓存的组件的组件名,和对应的方法
export default new Vuex.Store({
state: {
includeList: []
},
mutations: {
SET_INCLUDELIST: (state, includeList) => {
state.includeList = includeList
}
}
})
3、在AppMain.vue中
<keep-alive :include="includeList">
<router-view :key="key" />
</keep-alive>
<script>
import {
mapState
} from 'vuex'
export default {
name: 'AppMain',
computed: {
key() {
return this.$route.path
},
...mapState({
includeList: (state) => state.app.includeList
})
}
}
</script>
4、在beforeRouteLeave钩子函数里控制需要缓存的组件
注意:beforeRouteLeave导航守卫是必须写在当前单页面中,不能写在App.vue中
beforeRouteEnter(to, from, next) {
// 进入之前缓存本组件,解决第一次不缓存列表页的问题
next((vm) => {
vm.$store.commit("SET_INCLUDELIST", ["good-list"]);
});
},
beforeRouteLeave(to, from, next) {
// 跳转到详情页时缓存当前列表页,反之不缓存
if (to.path.indexOf("good-detail") > -1) {
this.$store.commit("SET_INCLUDELIST", ["good-list"]);
} else {
this.$store.commit("SET_INCLUDELIST", []);
this.$destroy(); // 销毁vue实例
}
next();
}