【C端】底部导航栏实现
思路:使用 watch 监听路由,实时更新高亮的标签
<template><RouterView /><van-tabbar v-model="active" @change="onTabChange"><van-tabbar-item v-for="tab in tabs" :key="tab.path" :icon="tab.meta.icon">{{ tab.meta.name }}</van-tabbar-item></van-tabbar>
</template>
① 当点击其他标签时,active 的值发生变化, 触发 onTabChange 事件:
import { ref, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'const active = ref(0)
const router = useRouter()
const route = useRoute()
const tabs = router.options.routes[0].children// 标签切换时的处理
function onTabChange(index) {const curRoute = `/${tabs[index].path}`if(curRoute !== route.path) {router.push(curRoute)}
}
② 使用 watch 监听路由的变化,当路由变化时,改变 active.value
watch(() => route.path,(newVal) => {// 根据当前路由自动激活对应 tabactive.value = tabs.findIndex(item => '/' + item.path === newVal)},{ immediate: true }
)
