Easy Accordion Component with VUE JS – Part 2
In part 1 of this tutorial, we learned how to create a simple accordion component using Vue.js. In this second part, we will expand on that and add more functionality to our accordion component.
Adding Multiple Sections
One of the main features of an accordion is the ability to have multiple sections that can be expanded and collapsed independently. To add this functionality to our accordion component, we can simply modify the data structure that holds the section information. Instead of having a single title and content, we can have an array of objects, each representing a section in the accordion.
<template>
<div>
<div v-for="section in sections" :key="section.id">
<h3 @click="toggleSection(section.id)">{{ section.title }}</h3>
<div v-show="section.open">{{ section.content }}</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
sections: [
{ id: 1, title: 'Section 1', content: 'Content for section 1', open: false },
{ id: 2, title: 'Section 2', content: 'Content for section 2', open: false },
{ id: 3, title: 'Section 3', content: 'Content for section 3', open: false }
]
};
},
methods: {
toggleSection(id) {
this.sections = this.sections.map(section => {
if (section.id === id) {
return { ...section, open: !section.open };
} else {
return { ...section, open: false };
}
});
}
}
};
</script>
Customizing Styles
Another important aspect of an accordion component is the ability to customize its appearance. With Vue.js, we can easily add classes and inline styles to the elements within our accordion component to achieve the desired look and feel. We can also utilize scoped styles to ensure that our styles do not leak out and affect other parts of the application.
<style scoped>
h3 {
cursor: pointer;
background-color: #f2f2f2;
padding: 10px;
margin: 0;
}
div {
padding: 10px;
background-color: #ffffff;
display: none;
}
div.show {
display: block;
}
</style>
Conclusion
With Vue.js, creating a customizable and feature-rich accordion component is easy and straightforward. By leveraging the reactivity system of Vue.js, we can create components that respond to user interaction and provide a great user experience. In this tutorial, we’ve added multiple sections and customized the styles of our accordion component, but the possibilities are endless. Be sure to experiment and make the accordion component your own!