vue2实现面包屑功能

目录

1. store/index.js

2. router/index.js

3. Header.vue


在Vue 2中实现面包屑导航是一种常见的前端实践,它可以帮助用户了解当前页面在网站结构中的位置,并快速导航到上一级或根目录。以下是使用Vue 2实现面包屑导航的基本步骤:

1. store/index.js

state中定义一个面包屑名称:currentPathName

mutations中定义一个方法:

export default new Vuex.Store({
  state: {
    currentPathName: ''
  },
  getters: {
  },
  mutations: {
    setPath (state) {
      state.currentPathName = localStorage.getItem('currentPathName')
    }
  },
  actions: {
  },
  modules: {
  }
})

2. router/index.js

使用路由守卫获取路由名称

router.beforeEach((to, from, next) => {
  // 设置当前的路由名称,为了在Header组件中去使用
  localStorage.setItem('currentPathName', to.name)
  // 触发store的数据更新
  store.commit('setPath')
  // 其他的情况都放行
  next()
})

3. Header.vue

<!--其它代码-->
<el-breadcrumb-item><a href="">{{ currentPathName }}</a></el-breadcrumb-item>
<!--其它代码-->
computed: {
  currentPathName () {
    return this.$store.state.currentPathName
  }
}
<!--其它代码-->

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
Vue 2中实现面包屑导航栏可以通过以下步骤完成: 1. 创建一个面包屑组件 `Breadcrumb.vue`: ```vue <template> <nav class="breadcrumb"> <ul> <li v-for="(crumb, index) in crumbs" :key="index" :class="{ active: index === crumbs.length - 1 }"> <router-link :to="crumb.path">{{ crumb.label }}</router-link> </li> </ul> </nav> </template> <script> export default { name: 'Breadcrumb', computed: { crumbs() { // 获取当前路由的路径 const routePath = this.$route.path; // 分割路径为数组 const pathSegments = routePath.split('/').filter(segment => segment !== ''); // 构建面包屑导航数据 const crumbs = pathSegments.map((segment, index) => { const path = `/${pathSegments.slice(0, index + 1).join('/')}`; return { path, label: segment }; }); return crumbs; } } }; </script> <style> .breadcrumb { background-color: #f5f5f5; padding: 10px; } .breadcrumb ul { list-style: none; padding: 0; margin: 0; } .breadcrumb li { display: inline-block; } .breadcrumb li:not(:last-child):after { content: '/'; margin: 0 5px; } .breadcrumb li.active { font-weight: bold; } </style> ``` 2. 在需要使用面包屑导航栏的组件中引入并使用 `Breadcrumb` 组件: ```vue <template> <div> <breadcrumb></breadcrumb> <!-- 其他组件内容 --> </div> </template> <script> import Breadcrumb from './Breadcrumb.vue'; export default { name: 'YourComponent', components: { Breadcrumb } }; </script> ``` 上述代码中,面包屑导航栏会根据当前路由的路径动态生成面包屑导航数据,并且只有最后一个路径会被标记为活动状态。你可以根据需要自定义样式和路由配置。希望对你有所帮助!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Java-云海

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值