项目中有类似需求:列表进详情,详情再返回列表,列表保持之前的状态,而其他页面进列表则重新渲染。
结合项目实际情况,最终实现方法:结合beforeRouteEnter和beforeRouteLeave钩子然后用keep-alive做缓存。
有关keep-alive的作用及使用方法本文将不再赘述(详见官方文档)
栗子如下,父组件:
<template> <div id="app"> <keep-alive :include="cachedPages"> <router-view /> </keep-alive> </div> </template> <script> import { mapState } from 'vuex' export default { computed: { ...mapState({ cachedPages: state => state.cachedPages }) } } </script>
列表组件:
export default { name: 'listComponentName', beforeRouteEnter(to, from, next) { next(vm => { vm.$store.commit('ADD_CACHED_PAGE', 'listComponentName') }) }, beforeRouteLeave(to, from, next) { // 详情组件路由假如是 /list/detail/123 if (!to.path.includes('/list/detail/')) { this.$store.commit('REMOVE_CACHED_PAGE', 'listComponentName') } next() } }
vuex:
export default new Vuex.Store({ state: { cachedPages: [] }, mutations: { ADD_CACHED_PAGE(state, payload) { !state.cachedPages.includes(payload) && state.cachedPages.push(payload) }, REMOVE_CACHED_PAGE(state, payload) { state.cachedPages = state.cachedPages.filter(item => item !== payload) } } })
有朋自远方来...评论一下呗O(∩_∩)O