• Vue动态缓存KeepAlive


    vue中keep-alive组件主要有三个常用的props。

    • 1,include存放的name是组件自身的name属性,只有名称匹配的组件会被缓存
    • 2,exclude,任何名称匹配的组件都不会被缓存
    • 3,max,最多可以缓存多少组件实例,一旦达到这个数字,那么缓存组件中最近没有被缓存的实例会被销毁

    这里使用 include 属性实现动态缓存,include 有3种传值方式:

    1. ‘组件A的name,组件B的name’
    2. ‘正则表达式1,正则表达式2’
    3. ‘[组件A的name,组件B的name]’

    实际开发过程中一般配合vue-router食用:

            <router-view>

    思路:通过将 aliveRoutes 加入Vuex进行状态管理,然后通过actions来动态改变aliveRoutes。具体实现如下:

    1. // store/async-router.js
    2. state: {
    3. ...
    4. aliveRoutes: []
    5. },
    6. mutations: {
    7. UPDATE_ALIVE_ROUER: (state, data) => {
    8. state.aliveRoutes = data
    9. },
    10. },
    11. actions: {
    12. ...
    13. addAliveRouter({ commit, state }, routerName) {
    14. if (!routerName) return
    15. const originData = state.aliveRoutes || []
    16. originData.push(routerName)
    17. const arr = Array.from(new Set(originData))
    18. commit('UPDATE_ALIVE_ROUER', arr)
    19. },
    20. delAliveRouter({ commit, state }, routerName) {
    21. const originData = state.aliveRoutes || []
    22. const index = originData.indexOf(routerName)
    23. if (!routerName || index === -1) return
    24. originData.splice(index, 1)
    25. commit('UPDATE_ALIVE_ROUER', originData)
    26. },
    27. }
    1. // xxx.vue
    2. ...
    3. export default {
    4. name: 'componentA', // 注意name需要与 aliveRoutes 中保持一致
    5. beforeRouteLeave(to, from, next) {
    6. next()
    7. // 判断如果返回首页则移除keepalive 否则保持缓存
    8. if (to.path === 'index') {
    9. // 移除 aliveRoutes 中的 componentA
    10. this.$store.dispatch('delAliveRouter', 'componentA')
    11. }
    12. },
    13. created() {
    14. // 初始化时增加 componentA 到 aliveRoutes
    15. this.$store.dispatch('addAliveRouter', 'componentA')
    16. },
    17. ...
    18. }

    在初始化路由时可以将路由中需要缓存的组件的name添加到 aliveRoutes  中

    1. import store from '@/store'
    2. // 加载默认需要keep alive的路由
    3. allRoutes.forEach(route => {
    4. const { meta, name } = route
    5. if (meta && meta.keepAlive) store.dispatch('addAliveRouter', name)
    6. })
    7. ...

  • 相关阅读:
    vue3 的 ref、isRef、toRef、toRefs、toRaw 详细介绍
    netapp3210存储更换故障硬盘过程
    科普达人丨一文看懂阿里云的秘密武器“神龙架构”
    html关闭空标签
    解决传统难题,WMS系统实现信息数据实时追踪
    【docker配置mysql主从复制模式】
    力扣栈与队列--总结篇
    无线局域网(WLAN)简单概述
    开启Hyper-v,使用蓝叠模拟器进行抓包的曲折经历
    java编写交换字符
  • 原文地址:https://blog.csdn.net/zg97zb/article/details/136374831