vue tab嵌入iframe切換不刷新,相對完整的方案

說到Vue的簡單、便捷、高效,誰用誰喜歡,天然企業應用也來玩一把,三大經典組件:樹控件,網格控件,選項卡控件;vue

 

本章先說選項卡tab控件的嵌入iframevue-router

 

本次主要解決如下問題:segmentfault

1.tab控件混合vue-component-view與iframe-view;app

2.切換tab, iframe-view 保持原界面不刷新,與keep-alive效果等同;this

3.關閉tab中的iframe-view後,將從新打開,不做cache;spa

 

 

問題1:code

 

將 <router-view></router-view> 與 iframe-view 列表 分開渲染component

大師兄的案例 中能夠學到,tab切換iframe-view不刷新的原理是:渲染iframe列表,並經過匹配當前路由名稱 v-show="$route.path === item.path"  控制切換顯示router

其中一個iframe-view;而router-view列表中,對應的component爲空即沒有內容顯示blog

 

P:其中一個 iframe-view

<template>
    <iframe width="500px" height="500px" src="http://www.baidu.com"></iframe>
</template>

P: 跳轉路由App-view

<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>

 

 

問題2:

關鍵點在於: 不使用默認component 屬性,自定義的屬性iframeComponent取而代之,手動注入組件,防止掛載組件致使從新渲染刷新;

import Vue from 'vue/dist/vue.js' import App from './App.vue' import VueRouter from 'vue-router'; import F1 from './components/f1'; import F2 from './components/f2'; const Index = { template: '<div>Index</div>' } const routes = [ { path: '/f1', name: 'f1', iframeComponent: F1 }, { path: '/f2', name: 'f2', iframeComponent: F2 }, { path: '/index', component: Index, children: [ { path: '/f3', iframe: true } ] } ] const router = new VueRouter({ routes // (縮寫)至關於 routes: routes
}); Vue.config.productionTip = false Vue.use(VueRouter); new Vue({ render: h => h(App), router }).$mount('#app')

 

 

問題3:

當你已經將iframe-view達到keep-alive的效果時,已經成功了一半,殊不知關閉tab後,iframe-view的真身還存在,只是v-show=false隱藏而已,再次打開時仍是上次的樣子,此時顯示應該是一個新的tab顯示。

解決此問題的關鍵點是:關閉tab時必須將它從iframe-view列表中移除,再次打開將它加入到列表中, computed過濾出iframe

computed: { hasOpenComponentsArr() { return this.$router.options.routes.filter(item => item.iframeComponent); } },

 

add / remove 方法可自行補充,此人懶沒辦法。。。

相關文章
相關標籤/搜索