vue结合keep-alive和vuex给页面做动态缓存
[ 2019/10/31, Vue , 1331阅, 0评 ]

项目中有类似需求:列表进详情,详情再返回列表,列表保持之前的状态,而其他页面进列表则重新渲染。

结合项目实际情况,最终实现方法:结合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