vue中keep-alive组件主要有三个常用的props。
这里使用 include 属性实现动态缓存,include 有3种传值方式:
实际开发过程中一般配合vue-router食用:
思路:通过将 aliveRoutes 加入Vuex进行状态管理,然后通过actions来动态改变aliveRoutes。具体实现如下:
- // store/async-router.js
- state: {
- ...
- aliveRoutes: []
- },
- mutations: {
- UPDATE_ALIVE_ROUER: (state, data) => {
- state.aliveRoutes = data
- },
- },
- actions: {
- ...
- addAliveRouter({ commit, state }, routerName) {
- if (!routerName) return
- const originData = state.aliveRoutes || []
- originData.push(routerName)
- const arr = Array.from(new Set(originData))
- commit('UPDATE_ALIVE_ROUER', arr)
- },
- delAliveRouter({ commit, state }, routerName) {
- const originData = state.aliveRoutes || []
- const index = originData.indexOf(routerName)
- if (!routerName || index === -1) return
- originData.splice(index, 1)
- commit('UPDATE_ALIVE_ROUER', originData)
- },
- }
- // xxx.vue
-
- ...
-
- export default {
- name: 'componentA', // 注意name需要与 aliveRoutes 中保持一致
- beforeRouteLeave(to, from, next) {
- next()
- // 判断如果返回首页则移除keepalive 否则保持缓存
- if (to.path === 'index') {
- // 移除 aliveRoutes 中的 componentA
- this.$store.dispatch('delAliveRouter', 'componentA')
- }
- },
- created() {
- // 初始化时增加 componentA 到 aliveRoutes
- this.$store.dispatch('addAliveRouter', 'componentA')
- },
- ...
- }
在初始化路由时可以将路由中需要缓存的组件的name添加到 aliveRoutes 中
- import store from '@/store'
-
- // 加载默认需要keep alive的路由
- allRoutes.forEach(route => {
- const { meta, name } = route
- if (meta && meta.keepAlive) store.dispatch('addAliveRouter', name)
- })
-
- ...