Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript Vue.js Basics Sweeping Vues: Loops, Methods, Directives Conditionally Adding or Removing Classes

Erica Leverson
Erica Leverson
8,663 Points

vue accordion close all accordions except one which is clicked on

How to add interactivity to close all other accordions except the one is clicked?

1 Answer

// add this to your methods in your javascript file

// showInfoInit is design to accept the status, media and index of each card
        // this allows us to check the status of the card, meaning if the card is open or closed
        // At first all cards are closed, thus we will fall to the else statement which
        // call the showInfo method
        showInfoInit: function(status, mediaList, index) {
          if(status){
            mediaList[index].showDetail = !mediaList[index].showDetail;
          } else {
            this.showInfo(mediaList, index);
          }
        },
        // showInfo takes 2 parameters; media and index
        // media holds the array of cards and index holds the value of the card being clicked on
        // inside this method we use for loop to run through each card and do the following:
        // if i(the number that increases each time the loop runs) is === index(the index of the clicked card)
        // we set that card's showDetail to true, which will make it open card and it will show the information
        // else sets all other cards' showDetail to false because they fail the if statement 
        showInfo: function(mediaList, index) {
          for (let i = 0; i < mediaList.length; i++) {
            if (i === index){
              mediaList[i].showDetail = true;
            } else {
              mediaList[i].showDetail = false;
            }
          }
        }
  • and also change the v-on:click in your li element to this:
v-on:click='showInfoInit(mediaList[index].showDetail ,mediaList, index)'
  • If you need help with anything else, let me know.

I uploaded the project to github, here is the link if you need help with structuring it.