解决办法:

第一步: 设置iframe页面路由标识

第二步: 原有的vue路由导航页面不变,判断存在$route.meta.iframe的页面走一下组件渲染;

对于vue项目的框架布局,iframe页面的判断放在tagsView.vue中

 第三步: 通过v-show对存在iframe的页面进行缓存

<template>
    <div>
        <!-- Vue的router-view -->
        <keep-alive>
            <router-view></router-view>
        </keep-alive>

        <!-- iframe页 -->
        <component
            v-for="item in hasOpenComponentsArr"
            :key="item.name"
            :is="item.name"
            v-show="$route.path === item.path"
        ></component>
    </div>
</template>

<script>
import Vue from 'vue/dist/vue.js'
export default {
    created() {
        // 设置iframe页的数组对象
        const componentsArr = this.getComponentsArr();
        componentsArr.forEach((item) => {
            Vue.component(item.name, item.component);
        });
        this.componentsArr = componentsArr;
        // 判断当前路由是否iframe页
        this.isOpenIframePage();
    },
    data() {
        return {
            componentsArr: [],
            
iframeArr: []
        }
    },
    watch: {
        $route() {
            // 判断当前路由是否iframe页
            this.isOpenIframePage();
        }
    },
    computed: {
        // 实现懒加载,只渲染已经打开过(hasOpen:true)的iframe页
        hasOpenComponentsArr() {
            console.log(this.componentsArr.filter(item => item.hasOpen))
            return this.componentsArr.filter(item => item.hasOpen);
        }
    },
    methods: {
        // 根据当前路由设置hasOpen
        isOpenIframePage() {
            const target = this.componentsArr.find(item => {
                return item.path === this.$route.path
            });
            if (target && !target.hasOpen) {
                target.hasOpen = true;
            }
        },
        // 遍历路由的所有页面,把含有iframeComponent标识的收集起来
        getComponentsArr() {
            debugger
            const router = this.$router;
            const routes = router.options.routes;
            this.getIframe(routes)
            return this.iframeArr.map((item) => {
                const name = item.name || item.path.replace('/', '');
                return {
                    name: name,
                    path: item.path,
                    hasOpen: false, // 是否打开过,默认false
                    component: item.iframeComponent // 组件文件的引用
                };
            });
        },
        getIframe(routes) {
            routes.map(item => {
                if(item.iframeComponent) {
                        this.iframeArr.push(item)
                }
                if(item.children && item.children.length > 0) {
                    this.getIframe(item.children)
                }
            })
    
        }
    }
}
</script>

以上步骤下来实现iframe页面tab切换时,不会重新加载页面。

 

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐