返回
基于 Vue.js 的 Matched 的实现,创造出优化的面包屑功能
前端
2024-01-13 00:03:58
概述
在构建大型单页面应用时,面包屑导航是一个非常有用的工具,它能帮助用户轻松了解自己的位置并能在多层级页面间快速导航。
使用 vue-router 的 matched 来实现面包屑
vue-router 是一个非常流行的 Vue.js 路由库,它提供了一个 matched
数组,其中包含了当前激活的路由记录。我们可以使用这个数组来实现面包屑导航。
实现步骤
- 首先,我们需要在 Vue.js 组件中创建一个数据属性来存储面包屑项目。
- 然后,我们需要在
created()
生命周期钩子中使用this.$router.currentRoute.matched
来获取当前激活的路由记录,并将它们存储到数据属性中。 - 接下来,我们需要创建一个模板来显示面包屑项目。我们可以使用
<ol>
和<li>
标签来创建一个有序列表,并将每个面包屑项目显示在<li>
标签中。 - 最后,我们需要在路由切换时更新面包屑项目。我们可以使用
watch
方法来监听this.$route
的变化,并更新数据属性中的面包屑项目。
示例代码
export default {
data() {
return {
breadcrumbs: []
}
},
created() {
this.breadcrumbs = this.$router.currentRoute.matched.map(record => ({
path: record.path,
name: record.meta.title
}))
},
watch: {
'$route' (to, from) {
this.breadcrumbs = to.matched.map(record => ({
path: record.path,
name: record.meta.title
}))
}
}
}
<template>
<ol class="breadcrumb">
<li v-for="breadcrumb in breadcrumbs" :key="breadcrumb.path">
<router-link :to="breadcrumb.path">{{ breadcrumb.name }}</router-link>
</li>
</ol>
</template>
总结
通过结合 matched
数组,你能够毫不费力地实现面包屑导航。面包屑导航的本质就是使用一个有序列表,分层显示用户当前位置,并为其提供返回上一层或更上一层页面的快捷方式。使用 Vue.js 的 matched 数组可轻松实现面包屑功能,同时保留路由的动态性与灵活性。赶快将面包屑功能添加到你的项目中,让用户轻松穿梭于页面,尽享便捷操作!