[Vuejs]-Nested v-for access from clicked child element to parent element

0👍

You can change your event handler to openModal (without the brackets and parameters). Then define your method to receive an event like so:

<a @click="openModal">{{subItem.name}}</a>

openModal(event) {
 // use event.target to get the element and then you can *walk* the dom
}

You can use element attributes to get your subitem.

You can also consider just passing an ID through.

0👍

Here it is, Pass dynamic value to the click event and capture it in ‘methods’ object.

var example1 = new Vue({
  el: '#example-1',
  data: {
    items: [
      { message: 'Foo' },
      { message: 'Bar' }
    ]
  },
	methods: {
  	openModal: function(message) {
     console.log(message);
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<ul id="example-1">
  <li v-for="item in items">
    <a @click='openModal(item.message)'>{{item.message}}</a>
  </li>
</ul>

Hope this helps.

0👍

Just to expand on Melas’ solution and provide some demo. Credit goes to Melas.

new Vue({
  el: '#app',

  data() {
    return {
      bubles: [{
          name: 'item 1',
          bubles: [
            { name: 'item 1.1' }
          ]
        },
        {
          name: 'item 2',
          bubles: [
            { name: 'sub-item 2.1' },
            { name: 'sub-item 2.2' },
            { name: 'sub-item 2.3' }
          ]
        },
        {
          name: 'item 3',
          bubles: [
            { name: 'sub-item 3.1' },
            { name: 'sub-item 3.2' }
          ]
        }
      ]
    }
  },

  methods: {
    openModal(evt) {
      if (evt.target) {
        // Not recommended, but you get the idea
        let parent = evt.target.parentElement.parentElement;

        // If you don't need to support IE, use this instead
        // parent = evt.target.closest('.parent-buble');

        parent.classList.add('highlight');

        // For demo purposes only
        setTimeout(() => {
          parent.classList.remove('highlight');
        }, 1000);

        console.log(parent);
      }
    }
  }
})
div.buble {
  cursor: pointer;
}

div.buble.highlight {
  color: crimson;
  font-weight: bold;
}

.child-buble {
  margin-left: 15px;
  color: #000;
  font-weight: normal;
}

.child-buble:active {
  color: crimson;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <div v-for="(item, index) in bubles" :key="item.name" class="buble parent-buble">
    {{item.name}}

    <div v-for="subItem in item.bubles" :key="subItem.name" class="buble child-buble">
      <a @click="openModal($event)">{{subItem.name}}</a>
    </div>
  </div>
</div>

Leave a comment