一般使用底部導航的方法是:在需要導航的頁面中加 導航組件,在這個導航組件中處理頁面跳轉行為
如果使用keepalive緩存頁面, 可能會有一些不正常表現:
1、頁面切換,導航組件不重新渲染
2、導航title 高亮錯誤,即,點擊A頁面標題,亮起來的卻是B頁面標題
處理方法:
1、在使用 導航組件時,添加key, 如: <TabBar key='A' />
2、在導航組件中,要確保本頁面的導航標題正確激活
下面是一個導航組件:
<template>
<van-tabbar v-model="activeTabbar" @change="onTabbarChange">
<van-tabbar-item icon="home-o">A</van-tabbar-item>
<van-tabbar-item icon="contact">B</van-tabbar-item>
<van-tabbar-item icon="friends-o">C</van-tabbar-item>
</van-tabbar>
</template>
<script lang="ts">
import { defineComponent, ref } from 'vue'
import { useRouter, useRoute } from 'vue-router'
export default defineComponent({
name: 'TabBar',
setup() {
const router = useRouter()
const route = useRoute()
const activeTabbar = ref(0)
setActiveTabbar()
function setActiveTabbar() {
switch (route.name) {
case 'A':
activeTabbar.value = 0
break
case 'B':
activeTabbar.value = 1
break
case 'C':
activeTabbar.value = 2
break
default:
}
}
function onTabbarChange(index: number) {
// 保持本頁面中的激活狀態。點擊導航標題 會改變本頁中activeTabbar的值,
// 如果開啟頁面緩存,那么再次進入此頁面就不會重新初始化activeTabbar,所以要在路由跳轉前恢復activeTabbar
setActiveTabbar()
switch (index) {
case 0:
router.push({ name: 'A' })
break
case 1:
router.push({ name: 'B' })
break
case 2:
router.push({ name: 'C' })
break
default:
}
}
return {
activeTabbar,
onTabbarChange
}
}
})
</script>
