[Vuejs]-Clicking on array element (object) shows wrong menu

3👍

Keep it all inside Vue. Use Vue to manage the state of the DOM, not IDs and CSS.

new Vue({
  el: "#app",
  data: () => ({
    selected: '',
    persons: [{
      'name': "Joe",
      "a": "1",
      "b": "2",
      "c": "3"
    }, {
      'name': "Jane",
      "a": "4",
      "b": "5",
      "c": "6"
    }, {
      'name': "Joe",
      "a": "7",
      "b": "8",
      "c": "9"
    }]
  }),
  computed: {
    filtered() {
      return this.groupBy(this.persons, 'name');
    }
  },
  methods: {
    toggle(index) {
      this.selected = index === this.selected ? '' : index
    },
    groupBy(array, key) {
      const result = {}
      array.forEach(item => {
        if (!result[item[key]]) {
          result[item[key]] = []
        }
        result[item[key]].push(item)
      })
      return result
    }
  }
});
.dropbtn {
  background-color: #04AA6D;
  color: black;
  padding: 16px;
  font-size: 16px;
  border: 2px solid #ccc;
  width: 100%;
  height: 3em;
}

td {
  height: 10px;
  padding: 2px;
}

dropdown {
  position: relative;
  display: inline-block;
}

.dropdown-content {
  position: absolute;
  left: 0;
  background-color: #f9f9f9;
  box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2);
}
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<div id="app">
  <table id="bigtable">
    <tr class="dropdown" v-for="(person, index) in filtered">
      <td>
        <button class="dropbtn" @click="toggle(index)">+ {{person[0].name}}</button>
        <div class="dropdown-content" v-if="index === selected">
          <table style="width:100%">
            <tr>
              <th>a</th>
              <th>b</th>
              <th>c</th>
            </tr>
            <tr v-for="item in person">
              <td>{{ item.a }}</td>
              <td>{{ item.b }}</td>
              <td>{{ item.c }}</td>
              <td>{{ item.cve }}</td>
            </tr>
          </table>
        </div>
      </td>
    </tr>
  </table>
</div>

Leave a comment