Vue 封装面包屑组件教程 - 详细步骤及代码示例
面包屑是指在网页中展示当前页面所在位置的导航路径,通常位于页面的顶部。下面是一个简单的实现 Vue 封装面包屑的步骤:
-
创建一个面包屑组件,可以使用 Vue 的单文件组件(.vue 文件)或者普通的 Vue 组件。
-
在组件中定义一个数组来存储面包屑的数据,例如:
crumbs = [{name: '首页', path: '/'}, {name: '分类', path: '/category'}, {name: '衣服', path: '/category/clothes'}, {name: '裤子', path: '/category/clothes/pants'}],其中每个对象表示一个面包屑项,包含两个属性:name表示面包屑的名称,path表示面包屑的链接路径。 -
在组件的
template中使用v-for指令循环遍历crumbs数组,生成面包屑项的 HTML 代码。 -
在组件中添加一个
props属性,用来接收父组件传递的面包屑数据,例如:props: ['crumbs']。 -
在父组件中通过
props属性传递面包屑数据到面包屑组件中,例如:<breadcrumb :crumbs='crumbs'></breadcrumb>,其中breadcrumb是面包屑组件的名称。 -
在页面的路由变化时,根据当前页面的路由信息来更新面包屑数据,可以使用 Vue Router 的导航守卫函数
beforeEach来实现。 -
在导航守卫函数中获取当前页面的路由信息,并根据路由信息来更新面包屑数据,例如:
router.beforeEach((to, from, next) => {
let crumbs = []
let matchedRoutes = to.matched.slice()
matchedRoutes.forEach(route => {
crumbs.push({
name: route.meta.title,
path: route.path
})
})
store.commit('setCrumbs', crumbs)
next()
})
其中 matchedRoutes 是一个数组,包含当前页面的所有路由记录,通过遍历 matchedRoutes 来获取每个路由记录的 meta.title 属性和 path 属性,分别作为面包屑项的名称和链接路径。最后将更新后的面包屑数据存储到 Vuex 的 store 中,供面包屑组件使用。
- 在面包屑组件中通过计算属性来获取 Vuex
store中存储的面包屑数据,例如:
computed: {
crumbs () {
return this.$store.state.crumbs
}
}
这样就完成了 Vue 封装面包屑的实现。
原文地址: https://www.cveoy.top/t/topic/mkGW 著作权归作者所有。请勿转载和采集!