1

I'm Building a tree-like structure in vue. I tried to do this with the data function but in that case, all the elements in the same level of the tree getting these classes although I just want clicked element to achieve this I tried this with the ref but don't know how to achieve that parent element selector part with it as I'm new to Vue till now i don't know how to tackle this .

this.parentElement.querySelector(".nested").classList.toggle("active");
this.classList.toggle("caret-down");
Nikola Pavicevic
  • 21,952
  • 9
  • 25
  • 46
Abbas Shaikh
  • 304
  • 1
  • 9

1 Answers1

0

Please take a look at one of solutions (if I understood you correctly) in following snippet

new Vue({
  el: '#demo',
  data() {
    return {
      tree: [
        {parent: 'AAA', childs: []},
        {parent: 'BBB', childs: [{child: 'bbb'}, {child: 'ccc'}]},
        {parent: 'CCC', childs: [{child: 'ddd'}, {child: 'eee'}, {child: 'fff'}]},
        {parent: 'DDD', childs: []}
      ],
      selected: null,
      active: null
    }
  },
  methods: {
    select(item, idx) {
      if (this.tree[idx].childs.length) {
        this.selected = idx
        this.active = null
      } else {
        this.active = item.parent + idx
        this.selected = null
      }
    },
    activate(itm, i) {
      this.active = itm.child + i
    }
  }
})
li {
 cursor: pointer;
}
.active {
  color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="demo">
  <ul>
    <li v-for="(item, idx) in tree" :key="idx">
      <p @click="select(item, idx)" :class="active === item.parent + idx ? 'active' : ''">{{ item.parent }}</p>
      <ul v-if="selected === idx">
        <li v-for="(itm, i) in item.childs" :key="i">
          <p @click="activate(itm, i)" :class="active === itm.child + i ? 'active' : ''">{{ itm.child }}</p>
        </li>
      </ul>
    </li>
  </ul>
</div>
Nikola Pavicevic
  • 21,952
  • 9
  • 25
  • 46