• vue3 动态修改 keepAlive


    需求场景:

    跳转逻辑A跳转 B,B页面 表单填写过程中 跳转 选择地址等额选项时,我们需要将B页面 进行 keepAlive 缓存,达到 返回时不重新渲染

    但是我们需要考虑 从 A 页面到 B 页面 需要全部重新加载,此类场景 我们需要 动态的去控制 keepAlive

    流程图 A页面 > B页面(表单页面) < 互相跳转 > C页面(额外选项 选择地址类似)

    App.vue

    <!-- vue3.0配置 -->
    <router-view v-slot="{ Component }">
        <keep-alive>
            <component :is="Component" :key="route.name" v-if="route.meta.keepAlive" />
        </keep-alive>
        <component :is="Component" :key="route.name" v-if="!route.meta.keepAlive" />
    </router-view>
    复制代码
    import { useRoute } from 'vue-router';
    export default defineComponent({
      name: 'App',
      setup(props) {
          const route = useRoute();
          return { route }
      }
    })
    复制代码

    router.ts

    // ...
    {
        path: 'path/BComponent',
        name: 'BComponent',
        component: BComponent,
        meta: {
            title: 'Page B',
            keepAlive: true
        }
    },
    {
        path: 'path/CComponent',
        name: 'CComponent',
        component: CComponent,
        meta: {
            title: 'Page C',
            keepAlive: false
        }
    },
    复制代码

    B.vue

    import { useRouter, useRoute, onBeforeRouteLeave } from 'vue-router';
    export default defineComponent({
      name: 'B',
      setup(props) {
          const route = useRoute();
          const router = useRouter();
          const changeRouterKeepAlive = (name: string, keepAlive: boolean) => {
    	router.options.routes.map((item: any) => {
                if (item.name === name) {
                        item.meta.keepAlive = keepAlive;
                }
    	});
          };
    
          onBeforeRouteLeave((to, from) => {
    	if (to.name !== 'c') {
                // 不是去 c 页面,不缓存
                changeRouterKeepAlive(from.name as string, false);
    	} else {
                changeRouterKeepAlive(from.name as string, true);
    	}
          });
    
          return { };
      }
    })
    复制代码
  • 相关阅读:
    性能优化之
    gruntjs开发实例
    从数组里随机获取N项
    调试工具-fiddler:本地资源替换线上调试
    HTML5-canvas实例:2D折线数据图与2D扇形图
    移动前端兼容性笔记
    Less开发指南(三)- 代码文件跟踪调试
    像纸质笔记本一样给div,textarea添加行的分割线
    基于视图的增删改查操作(颠覆传统思维吧)
    恶劣的百度推广人员
  • 原文地址:https://www.cnblogs.com/richard1015/p/15602870.html
Copyright © 2020-2023  润新知