MK01111000
MK01111000

Reputation: 832

How do I toggle (hide/unhide) child elements of dynamically added components with v-for

The following renders a header text and some child elements. What I would like to accomplish is that the child elements toggle (hide/unhide) when the header is clicked. So in below example, when Spanish01 is clicked, all its children should be hidden and when its clicked again the should reappear. I tried to find a similar case on the internet but could not find any. All help is welcome

enter image description here

  <div id="dashboard">
    <ul class="collection with-header">
      <li class="collection-header"><h4>Cards</h4></li>
      <li v-for="card in cards" v-bind:key="card.id" class="collection-item">
        <div class="chip">{{card.group_name}}</div>
        <ul class="collection with-header">
          <li v-for="(value, index) in card.group" v-bind:key="index" class="collection-item">
            <ul>
              <li>
                front: {{value.front}}
              </li>
              <li>
                back: {{value.back}}
              </li>
            </ul>
          </li>
        </ul>
      </li>
    </ul>
  </div>

Upvotes: 0

Views: 415

Answers (1)

Sumurai8
Sumurai8

Reputation: 20737

You can simply put an extra variable on each of your cards. Then you can do something like this:

  <div id="dashboard">
    <ul class="collection with-header">
      <li class="collection-header"><h4>Cards</h4></li>
      <li v-for="card in cards" v-bind:key="card.id" class="collection-item">
        <div class="chip" @click="card.shown = !card.shown>{{card.group_name}}</div>
        <ul class="collection with-header" v-show="card.shown">
          <li v-for="(value, index) in card.group" v-bind:key="index" class="collection-item">
            <ul>
              <li>
                front: {{value.front}}
              </li>
              <li>
                back: {{value.back}}
              </li>
            </ul>
          </li>
        </ul>
      </li>
    </ul>
  </div>

Obviously, you have to alter your variable cards so it contains the shown attribute by default. As an alternative, you can set up a different variable that contains the shown status and use some unique id to look up the value instead.

Upvotes: 1

Related Questions