- 路由嵌套
- 封装tabbar组件
- 创建一个容器放tabbar和子路由
- keep-alive保存路由状态
1.路由嵌套
{
path: '/',
name: 'index',
component: () => import('@/views/index.vue'),
children:[
{
path: '',
redirect:'/com',
meta:{
keepAlive: true
}
},
{
path: '/com',
name: 'com',
component: () => import('@/views/com.vue'),
meta:{
keepAlive: true
}
},
{
path: '/info',
name: 'info',
component: () => import('@/views/info.vue'),
meta:{
keepAlive: true
}
},
{
path: '/mine',
name: 'mine',
component: () => import('@/views/mine.vue'),
meta:{
keepAlive: true
},
},
]
},
2.封装tabbar组件
src/components/tabbar
<template>
<div class='tabbarBox'>
<div class="tabbar-box" v-if="tabs.length > 0">
<div class="tabbar-item" v-for="(item, index) in tabs" :key="index"
:class="{ 'active': activeIndex === index }" @click="selectTab(index,item.path)">
{{ item.title }}
</div>
</div>
</div>
</template>
<script setup lang="ts">
// 接收参数
const props = defineProps({
tabs: {
type: Array,
default: () => { },
},
});
const router = useRouter()
const tabs = ref<any>([])
const activeIndex = ref<number>(0);
watchEffect(() => {
tabs.value = props.tabs;
});
const selectTab = (index:number,path:string) => {
activeIndex.value = index;
router.push(path)
};
onMounted(() => {
})
</script>
3.创建一个容器放tabbar和子路由
src/view/index.vue
网上都是把tabbar放在app.vue里边的,但是放在app.vue每个页面都会显示了还需要判断,直接弄一个容器专门放tabbar页面
<template>
<div class="tabbar">
<tabbar :tabs='tabs'/>
<router-view v-slot="{ Component }">
<keep-alive>
<component :is="Component" />
</keep-alive>
</router-view>
</div>
</template>
<script setup lang="ts">
interface Tab {
title: string;
path: string;
}
const tabs: Tab[] = [
{ title: '社区', path: '/com' },
{ title: '消息', path: '/info' },
{ title: '我的', path: '/mine' },
];
onMounted(() => {
})
</script>
<style scoped lang='less'>
.tabbar {
width: 100vw;
height: 100vh;
background: #F7F6FB;
}
</style>
4.使用keep-alive
src/view/com.vue
<template>
<div class='com-page' ref="comPage">
<div class="com-box">社区</div>
</div>
</template>
<script setup lang="ts">
import { useTemplateRef } from 'vue';
const scrollTop = ref<number>(0);
const compage = useTemplateRef<HTMLElement>("comPage");
onActivated(() => {
nextTick(() => {
// 跳转后��复 scrollTop 值,在下次路由跳转时��复 scrollTop 值
if (compage.value) {
compage.value.scrollTop = scrollTop.value
}
})
})
onBeforeRouteLeave((to, from, next) => {
// 路由跳转前记录 scrollTop 值,在下次路由跳转时��复 scrollTop 值
if (compage.value) {
scrollTop.value = compage.value.scrollTop
}
next()
})
onMounted(() => {
})
</script>
<style scoped lang='less'>
.com-page {
width: 100vw;
height: 100vh;
background: #F7F6FB;
overflow: auto;
font-size: 80px;
.com-box {
height: 8000px;
}
}
</style>
useTemplateRef是vue3.5新发布的特性,用来获取dom
标签:vue,const,自定义,alive,keep,tabbar,scrollTop,path,路由 From: https://blog.csdn.net/weixin_54422862/article/details/142174510