vue+element 动态面包屑导航

在这里插入图片描述
核心代码

watch: {
  $route() {
    this.getBreadcrumb()
  }
}
methods: {
    getBreadcrumb() {
    
      console.log(this.$route.matched)  //可以获取上下文路由 也就是可以获取父亲和孩子路由组成的数组

      if (Object.keys(this.$route.matched[0].meta).length > 0) {
        this.breadList = this.$route.matched
      } else {
        this.breadList = []
      }
    }

  },
<el-breadcrumb separator="/">
  <el-breadcrumb-item
    :to="{ path: '/home' }"
  >
    首页
  </el-breadcrumb-item>
  <el-breadcrumb-item
    :to="{path: item.path}"
    v-for="(item, index) in breadList"
    :key="index"
  >

    {{item.meta.title}}
  </el-breadcrumb-item>
</el-breadcrumb>
对于Vue 3和Element Plus的动态面包屑导航,你可以按照以下步骤进行实现: 1. 首先,安装所需的依赖: ```bash npm install vue@next vue-router@4 element-plus ``` 2. 在你的Vue项目中,创建一个新的组件来表示面包屑导航,比如`Breadcrumb.vue`。 3. 在`Breadcrumb.vue`组件中,导入所需的组件和路由相关的方法: ```javascript <template> <el-breadcrumb separator-class="el-icon-arrow-right"> <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item> <el-breadcrumb-item v-for="(route, index) in routes" :key="index" :to="route.to">{{ route.name }}</el-breadcrumb-item> </el-breadcrumb> </template> <script> import { useRouter } from 'vue-router'; export default { setup() { const router = useRouter(); const routes = router.currentRoute.value.matched.map((route) => ({ name: route.meta.title, to: route.path, })); return { routes, }; }, }; </script> ``` 4. 在你的路由配置文件中,为每个路由添加`meta`字段并指定对应的面包屑名称: ```javascript const routes = [ { path: '/', component: Home, meta: { title: '首页', }, }, { path: '/about', component: About, meta: { title: '关于我们', }, }, // 其他路由配置... ]; ``` 5. 在你的页面组件中,使用`Breadcrumb`组件来展示动态面包屑导航: ```javascript <template> <div> <Breadcrumb /> <!-- 其他页面内容... --> </div> </template> <script> import Breadcrumb from './Breadcrumb.vue'; export default { components: { Breadcrumb, }, }; </script> ``` 这样,当你切换不同的路由时,面包屑导航将会根据当前路由自动更新。注意:在Vue 3中,我们使用了Composition API的`setup`函数来实现逻辑,同时使用了`useRouter`方法来获取当前路由信息。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值