[Vuejs]-Vue.js Parent Child communication via Props and Events

1๐Ÿ‘

Vue have one way data flow, so data can be passed from parent to child via props. You can emit events from child to parent as documented here

But given that you have many child components, I will recommend to use a central state machine, and vuex is a fine example of it which is quite popular as well in the community.

0๐Ÿ‘

Iโ€™ll suggest you to use vue-clickaway. This project is for this particular case where you want to listen to the clicks outside the component.

The use is pretty simple

import { mixin as clickaway } from 'vue-clickaway';

export default {
   mixins: [ clickaway ],
   template: '<p v-on-clickaway="away">Click away</p>',
   methods: {
      away: function() {
      console.log('clicked away');
    },
  },
};

I had used an eventbus when I had to do such a thing on my own. The eventbus is for such things where using a state could be overkill and emitting from each component might make it a mess.

0๐Ÿ‘

Thank you all for your help. I ended up calling a Method on every child.
I think this is the most logical way for me (I know there are several ways). Accessing the children is not very convenient, because I generate them in 2 nestet v-for loop. Not very elegant to access but it is working.

 var rows = this.$children[0].$children
      for(var j = 0;j<rows.length;j++){
        var row = rows[j].$children;
        for(var i = 0; i<row.length;i++){
         row[i].hideMenu();

      }


      }




  },

-1๐Ÿ‘

In parent:

this.$children[index].$emit('contextMenuShown', true);

In children:

mounted () {
    this.$on('contextMenuShown', function() {
        // Do stuff
    });
}

Leave a comment