目的
A:主页
B:列表页
C:详情页
详情页返回列表页,列表页缓存,主页到列表页不缓存
步骤
1.在router加上scrollBehavior方法
const router = new VueRouter({ routes, // eslint-disable-next-line no-unused-vars scrollBehavior (to, from, savedPosition) { return { x: 0, y: 0 } } });
2.在app.vue下增加keep-alive
<keep-alive :include="catchList"> <router-view></router-view> </keep-alive>
export default { name: 'App', computed:{ catchList(){ return this.$store.state.catchList; } }
这里的catchList,是vuex维护的需要缓存的组件名的一个数组。
3.在store里加入需要缓存的的组件的变量名,和相应的方法
export default new Vuex.Store({ state: { catchList:[] }, mutations:{ //缓存组件 keepAlive(state, component) { !state.catchList.includes(component) && state.catchList.push(component) }, //清空缓存 noKeepAlive(state) { state.catchList = [] } } })
4.在路由main.js中加入
router.beforeEach((to, from, next) => { if (to.name === 'B') { store.commit('keepAlive', 'B') } next() })
5.在b.vue中加入
beforeRouteLeave (to, from, next) { if (to.name !== 'C') { this.$store.commit('noKeepAlive') } next() }
注:只要跳转到B组件就缓存B。当从B>A的时候,B不缓存。
本文链接:https://jeff.xin/post/116.html
--EOF--
发表于 2020-06-01 ,并被添加「 Vue 」标签 。
Comments
发表评论:
◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。