Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get parent of clicked element in Vue.js

Tags:

vue.js

How to get parent of clicked (this) element in Vue.js? In jQuery this looks like:

$(this).parents(':eq(2)').next('.press__news__nav--view').show();

Thanks!

like image 490
Milan Milosev Avatar asked May 19 '17 10:05

Milan Milosev


People also ask

How do you get parent elements in Vue?

We can access the root Vue instance with $root , and the parent component with $parent . To access a child component from a parent, we can assign a ref with a name to the child component and then use this. $refs to access it.

How do you call parent method from child component in Vue?

To call parent method with component with Vue. js, we can get the parent component's method from the $parent property. to define the child component with Vue. component .

What is parent and child in Vue?

Parent To Child Communication In Vue. To move data from a parent component to a child component in Vue we use something called props. ReactJS also uses a similar convention for sharing data. Props is short for “properties” and is referring to properties set from outside, such as from the parent component.


1 Answers

It's not a good practice in Vue when you're trying to manipulate DOM directly. If you want to show/hide an element, you should use v-if or v-show directives.

Anyway, you can access event object like this:

new Vue({
  el: '#app',
  methods: {
    logme: function(event) { // a regular event object is passed by $event in template
      console.log(event.target.parentElement) // parent element
    }
  }
});
<script src="https://unpkg.com/vue/dist/vue.js"></script>

<div id="app">
  <div class="hello">
     <button @click="logme($event)">Click me</button>
  </div>
</div>
like image 78
Egor Stambakio Avatar answered Sep 29 '22 05:09

Egor Stambakio