返回
初学者必备!Vue3手把手教你封装面包屑组件
前端
2023-12-09 23:12:16
前言
面包屑导航组件是一种常用的前端UI元素,它可以帮助用户了解自己在网站或应用程序中的位置。它通常由一组链接组成,这些链接代表用户访问过的页面或部分。当用户点击面包屑链接时,他们将被带到该链接所代表的页面或部分。
在Vue3中,我们可以通过以下步骤手动封装一个简易的面面包屑组件:
- 准备静态的
shop-bread.vue
组件
<template>
<div class="breadcrumb">
<slot></slot>
</div>
</template>
<script>
export default {
name: 'ShopBread'
}
</script>
<style>
.breadcrumb {
display: flex;
align-items: center;
justify-content: flex-start;
flex-wrap: wrap;
padding: 0;
margin: 0;
list-style: none;
}
.breadcrumb li {
display: inline-block;
margin-right: 10px;
}
.breadcrumb a {
text-decoration: none;
color: #333;
}
.breadcrumb a:hover {
color: #000;
}
</style>
- 定义props暴露
parentPath
、parentName
属性,默认插槽,动态插槽
export default {
name: 'ShopBread',
props: {
parentPath: {
type: String,
default: ''
},
parentName: {
type: String,
default: ''
}
},
computed: {
crumbs() {
const crumbs = this.$slots.default
? [
{
path: this.parentPath,
name: this.parentName
},
...this.$slots.default
]
: []
return crumbs.filter(crumb => crumb.name)
}
},
render() {
return (
<div class="breadcrumb">
{this.crumbs.map((crumb, index) => (
<li key={index}>
<a href={crumb.path}>{crumb.name}</a>
</li>
))}
</div>
)
}
}
- 使用组件
<template>
<ShopBread parentPath="/" parentName="首页">
<li>
<a href="/category/1">分类一</a>
</li>
<li>
<a href="/product/1">产品一</a>
</li>
</ShopBread>
</template>
<script>
import ShopBread from '@/components/ShopBread.vue'
export default {
components: { ShopBread }
}
</script>
结语
以上就是如何手动封装一个简易的面包屑组件的教程。通过本教程,你应该已经掌握了面包屑组件的基本原理和实现方法。你还可以根据自己的需要,对组件进行进一步的定制和优化。