用component实现
时间: 2023-08-29 22:08:13 浏览: 29
使用组件实现侧边栏导航循环遍历icon的过程需要创建两个组件:
- `SidebarNav`:侧边栏导航组件,负责展示导航菜单和处理选中项;
- `SidebarNavItem`:侧边栏导航项组件,负责展示单个导航项和处理点击事件。
以下是一个示例代码:
`SidebarNav`组件:
```html
<template>
<div>
<ul>
<sidebar-nav-item v-for="(item, index) in navItems"
:key="index"
:item="item"
:index="index"
:active="index === activeIndex"
@select="handleSelect" />
</ul>
</div>
</template>
<script>
import SidebarNavItem from './SidebarNavItem.vue';
export default {
data() {
return {
activeIndex: 0, // 默认选中项的索引
navItems: [
{
title: "Home",
link: "/",
icon: "fas fa-home" // Font Awesome提供的icon类名
},
{
title: "About",
link: "/about",
icon: "fas fa-info-circle"
},
{
title: "Contact",
link: "/contact",
icon: "fas fa-envelope"
},
// 循环遍历的数据可以自行添加或从后端API获取
]
};
},
components: {
SidebarNavItem
},
methods: {
handleSelect(index) {
this.activeIndex = index;
this.$emit('select', this.navItems[index]);
}
}
};
</script>
```
在上面的代码中,我们使用`v-for`指令在`<ul>`元素中循环遍历`navItems`数组中的导航项,并将每个导航项作为`SidebarNavItem`组件的`item`属性传递给它。同时,我们使用`:active`属性将当前选中项的索引传递给`SidebarNavItem`组件,以便它可以设置相应的样式。在`handleSelect`方法中,我们监听`SidebarNavItem`组件的`select`事件,更新选中项的索引并执行相应的操作。最后,我们通过`$emit`方法向父组件发送`select`事件和选中的导航项对象。
`SidebarNavItem`组件:
```html
<template>
<li :class="{ active: active }" @click="handleClick">
<a :href="item.link">
<i :class="item.icon"></i> {{ item.title }}
</a>
</li>
</template>
<script>
export default {
props: {
item: {
type: Object,
required: true
},
index: {
type: Number,
required: true
},
active: {
type: Boolean,
required: true
}
},
methods: {
handleClick() {
this.$emit('select', this.index);
}
}
};
</script>
<style>
li.active {
background-color: #ccc;
}
</style>
```
在上面的代码中,我们使用`:class`属性动态设置导航项的样式,并通过`@click`事件监听导航项的点击事件。在`handleClick`方法中,我们向父组件发送`select`事件和当前导航项的索引。同时,我们使用`props`属性接收来自父组件的`item`、`index`和`active`属性,并根据它们的值设置相应的导航项样式。
使用这两个组件,我们可以在父组件中实现侧边栏导航循环遍历icon的功能:
```html
<template>
<div>
<sidebar-nav @select="handleSelect" />
</div>
</template>
<script>
import SidebarNav from './SidebarNav.vue';
export default {
components: {
SidebarNav
},
methods: {
handleSelect(item) {
console.log(item);
}
}
};
</script>
```
在上面的代码中,我们使用`SidebarNav`组件展示了侧边栏导航菜单,并监听它的`select`事件。在`handleSelect`方法中,我们可以获取选中的导航项对象并执行相应的操作。