Categories
Vue 3 Projects

Create an Accordion Component with Vue 3 and JavaScript

Spread the love

Vue 3 is the latest version of the easy to use Vue JavaScript framework that lets us create front end apps.

In this article, we’ll look at how to create an accordion component with Vue 3 and JavaScript.

Create the Project

We can create the Vue project with Vue CLI.

To install it, we run:

npm install -g @vue/cli

with NPM or:

yarn global add @vue/cli

with Yarn.

Then we run:

vue create accordion-component

and select all the default options to create the project.

Create the Accordion Component

To create the accordion component, we write:

<template>
  <div v-for="c of contents" :key="c.title">
    <div class="title" @click="c.expanded = !c.expanded">
      <div>
        <b>{{ c.title }}</b>
      </div>
      <div>
        <span v-if="c.expanded">&#x2191;</span>
        <span v-else>&#x2193;</span>
      </div>
    </div>
    <div class="description" v-if="c.expanded">
      {{ c.description }}
    </div>
  </div>
</template>

<script>
const contents = Array(10)
  .fill()
  .map((_, i) => {
    return {
      title: `title ${i}`,
      description: `description ${i}`,
      expanded: false,
    };
  });

export default {
  name: "App",
  data() {
    return {
      contents,
    };
  },
};
</script>

<style scoped>
.title {
  cursor: pointer;
  display: flex;
  justify-content: space-between;
}

.title,
.description {
  border: 1px solid black;
  padding: 5px;
}
</style>

We start by adding the elements for the accordion in the templaye.

We use the v-for directive to render the contents array into an accordion.

The key is set to the c.title property, which is unique.

In the inner div, we attached a click listener with the @click directive.

The click listener toggles the expanded property.

Inside it, we render the c.title property and show the down arrow if it’s not expanded, which is when c.expanded is false

And we show the up arrow when c.expanded is true .

c.description is rendered in the div below the title div.

It’s only shown with c.expanded is true .

Below that, we have the contents array to add some content to show.

In the data method, we return an object with the contents reactive property created from the contents array.

In the style tag, we have the title class selector’s styles set to cursor: pointer to set to a hand cursor.

display set to flex to enable flex layout.

This lets us use justify-content set to space-between to display the 2 divs at the left and right ends of the title div.

Then finally, we set the border and padding on the divs with the title and description classes styles.

We add a border and padding to these divs.

Now when we click on the title divs, we see the description divs toggled on and off.

Conclusion

We can create an accordion component easily with Vue 3 and JavaScript.

Leave a Reply

Your email address will not be published. Required fields are marked *