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>
