1. 程式人生 > 實用技巧 >vue 使用keep-alive快取tab切換元件,保持每個元件滾動條位置

vue 使用keep-alive快取tab切換元件,保持每個元件滾動條位置

vue專案中用到了tab切換,由於切換模組過多,都寫在同一組件中程式碼會越來越難維護,解決辦法就是把每個tab頁籤內容拆分成單獨的元件。

當然可以考慮直接每個tab頁單獨設定成一個路由,但有時候可能是彈出框中用到的tab切換,這時就不適用於路由來配置解決了。

這時可以使用component標籤的is屬性來動態切換元件,並配合keep-alive標籤快取元件,達到切換後保留元件填寫內容等操作狀態,並保持滾動條位置。

保持滾動條位置的功能是利用監聽tab變化時來獲取即將要切換走的元件外框的滾動條位置,在切換回來時在重新賦值其滾動位置。

為何不使用快取元件的 deactivated 觸發時來獲取其位置呢?因為deactivated執行較慢,拿不到滾動位置。

使用了element-ui元件庫

主體頁面如下:

<template>
  <div>
     <el-tabs v-model="currentTab">
       <el-tab-pane v-for="(item, index) in tabList" :key="index" :label="item.label" :name="item.name"></el-tab-pane>
     </el-tabs>
     <keep-alive>
      <component
        ref
="tab" :is="currentTab" ></component> </keep-alive> </div> </template> <script> import material from "./material"; import system from "./system"; export default { components: { material, system }, data() { return { currentTab:
'material', tabList: [ { "label": "素材圖片", "name": "material" }, { "label": "系統圖標", "name": "system" } ] } }, watch:{   currentTab(newValue) {   //切換時先記錄其wrapper容器的scrollTop,以便在切換回來時保持滾動到的位置   this.$refs.tab.scrollTop = this.$refs.tab.$refs.wrapper.scrollTop;   }  } } </script>

子元件公共部分: (一些公共的js可以抽取成mixin)

<template>
  <div ref="wrapper" style="overflow-y: auto;">
  </div>
</template>
<script>
    export default {
        data() {
          return {
          scrollTop: 0, //記錄滾動條位置
        }
      },
      activated() {
        //保持滾動到的位置
        this.$refs.wrapper.scrollTop = this.scrollTop;
       }
    }
</script>