Categories
JavaScript Vue

How to Add an Accordion to Our Vue App

Spread the love

We can use the vue-accordion to create a vertical accordion.

To use it we install it by running:

npm install vue-accordion

Next, we register the plugin in main.js:

import Vue from "vue";
import App from "./App.vue";
import { vueAccordion } from "vue-accordion";

Vue.component("vue-accordion", vueAccordion);
Vue.config.productionTip = false;

new Vue({
  render: h => h(App)
}).$mount("#app");

We called the Vue.component method to register the component.

Then we use it in our component by writing:

<template>
  <div id="app">
    <vue-accordion :items="items" :styles="styles"></vue-accordion>
  </div>
</template>

<script>
export default {
  name: "App",
  data() {
    return {
      items: [
        {
          title: "First",
          text: "First",
          url: "http://placekitten.com/200/200",
          image: "http://placekitten.com/200/200"
        },
        {
          title: "Second",
          text: "Second",
          url: "#",
          image: "http://placekitten.com/200/200"
        }
      ],
      styles: {
        div: {
          height: "350px"
        }
      }
    };
  }
};
</script>

We have the items array with objects that have the title, text, url, and image properties.

They are all required.

title is rendered as the title, text is the body. url is the URL to go to. image is the URL of the image to display.

styles has the styles we want to apply to each accordion item.

In the template, we use the vue-accordion component, which is made available by registering it earlier.

Noe we should see images displayed.

When we hover over the image then we should see our text.

And when we click on the item, then the browser would go to the URL set as the value of the url property.

Leave a Reply

Your email address will not be published.

If you like the content of this blog, subscribe to my email list to get exclusive articles not available to anyone else.