keep-live缓存组件笔记

448 阅读1分钟

Vuex文件store.js

export default {
  namespaced: true,
  state: {
    keepAliveComponents: [] // 缓存数组
  },
  mutations: {
    keepAlive (state, component) {
      // 注:防止重复添加(当然也可以使用Set)
      !state.keepAliveComponents.includes(component) && 
        state.keepAliveComponents.push(component)
    },
    noKeepAlive (state, component) {
      const index = state.keepAliveComponents.indexOf(component)
      index !== -1 &&
        state.keepAliveComponents.splice(index, 1)
    }
  }
}

使用的路由页面

<div class="app">
  <!--传入include数组-->
  <keep-alive :include="keepAliveComponents">
    <router-view></router-view>
  </keep-alive>
</div>
export default {
  computed: {
    ...mapState({
      keepAliveComponents: state => state.global.keepAliveComponents
    })
  }
}

路由配置页面 route.js

const router = new Router({
  routes: [
    {
      path: '/A/B',
      name: 'B',
      component: B,
      meta: {
        title: 'B页面',
        keepAlive: true // 这里指定B组件的缓存性
      }
    }
  ]
})
router.beforeEach((to, from, next) => {
  // 在路由全局钩子beforeEach中,根据keepAlive属性,统一设置页面的缓存性
  // 作用是每次进入该组件,就将它缓存
  if (to.meta.keepAlive) {
    store.commit('global/keepAlive', to.name)
  }
})

组件页面内取消缓存

export default {
  name: 'B',
  created () {
      // ...设置滚动条在最顶部
  },
  activated () {
  	  // 用于更新缓存数据
  },
  beforeRouteLeave (to, from, next) {
    // 如果下一个页面不是详情页(C),则取消列表页(B)的缓存
    if (to.name !== 'C') {
        this.$store.commit('global/noKeepAlive', from.name)
    }
    next()
  }
}

笔记参考 keep-alive:组件级缓存