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


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

 

本章先說選項卡tab控件的嵌入iframe

 

本次主要解決以下問題:

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

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

3.關閉tab中的iframe-view后,將重新打開,不作cache;

 

 

問題1:

 

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

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

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

 

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 方法可自行補充,此人懶沒辦法。。。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM