安装路由
npm i vue-router
配置四个页面,并注册路由
import { createWebHashHistory,createRouter } from "vue-router";
const routes=[
{
path:'/page1',
component:()=>import('../views/page1.vue')
},
{
path:'/page2',
component:()=>import('../views/page2.vue')
},
{
path:'/page3',
component:()=>import('../views/page3.vue')
},
{
path:'/page4',
component:()=>import('../views/page4.vue')
},
{
path:'/',
redirect:'/page1'
}
]
const router=createRouter({
history:createWebHashHistory(),
routes
})
export default router
app.vue
<template>
<!-- 面包屑部分 -->
<!-- 路由展示部分 -->
<router-view></router-view>
</template>
<script>
</script>
<style scoped lang="less">
</style>
面包屑组件
app.vue组件,使用组件bread,breaditem
<template>
<router-view></router-view>
</template>
<script setup>
import Bread from './components/bread.vue';
import BreadItem from './components/breaditem.vue'
</script>
<style scoped lang="less">
</style>
bread.vue组件,shiyongrender()组件动态创建节点
<script>
import { h } from 'vue';
export default{
render(){
// 拿到插槽的内容
const content=this.$slots.default()
// 使用中间变量存储breaditem插槽内容
const temp=[]
// 判断插槽是否是breaditem组件
content.forEach((item,i)=>{
// 是
if(item.type.name==='breaditem'){
temp.push(item)
// 如果当前项不是最后一个,加一个>符号,如page1>page2>page3
if(i<content.length-1){
// 加入一个span标签,内容是 >
temp.push(h('span','>'))
}
}
})
return h('span',temp)
}
}
</script>
<style scoped lang="less">
</style>
breaditem.vue组件
<template>
<span class="container">
<router-link :to="to">
<slot></slot>
</router-link>
</span>
</template>
<script>
export default{
name:'breaditem',
props:{
to:{
type:String,
default:''
}
}
}
</script>
<style scoped lang="less"></style>
面包屑跳转实现
给需要有面包屑的页面使用组件
page1.vue
<template>
<bread>
<breaditem to="/">page1</breaditem>
</bread>
<br>
<h1>page1路由内容</h1>
<button @click="$router.push('/page2')">去page2</button>
<br>
<router-view></router-view>
</template>
<script setup>
import bread from '../components/bread.vue';
import breaditem from '../components/breaditem.vue';
</script>
<style scoped lang="less"></style>
page2.vue
<template>
<bread>
<breaditem to="/">page1</breaditem>
<breaditem>page2</breaditem>
</bread>
<h1>page2路由内容</h1>
<button @click="$router.push('/page3')">去page3</button>
<br>
<RouterView>
</RouterView>
</template>
<script setup>
import bread from '../components/bread.vue';
import breaditem from '../components/breaditem.vue';
</script>
<style scoped lang="less"></style>
page3.vue
<template>
<bread>
<breaditem to="/">page1</breaditem>
<breaditem to="/page2">page2</breaditem>
<breaditem>page23</breaditem>
</bread>
<h3>page3内容</h3>
</template>
<script setup lang="ts">
import bread from '../components/bread.vue';
import breaditem from '../components/breaditem.vue';
</script>
<style scoped lang="less"></style>
效果展示