[Vuejs]-How to access child component data in v-if outside of component?

2👍

There are several ways to share data between parents / components such as 2-way binding between parent/child and also sending and listening for events.

Here is an events example with $broadcast and $dispatch:

parent vue:

var parentVue = new Vue({
     ...
     compiled: function(){
          this.$on('receiveDataFromChild', function(){
               //do something with the data from the child
          });
     },
     methods: {
          checkChildForData: function(){
               this.$broadcast('pleaseSendDataToYourMama');
          }
     }
}); 

child vue:

var childVue = new Vue({
     ...
     compiled: function(){
          this.$on('pleaseSendDataToYourMama', function(){
               this.$dispatch('receiveDataFromChild',this.someImportantData);
          });
     }
}); 

0👍

This is how I now have it working, I’m not sure this is the best way but I’m not getting any console.warn alerts in my console. Would love any feedback. Many thanks to @Douglas.Sesar

// child
Vue.component('student-table', {

    parent: vueApp,

    data: function () {
        return {
            selected: []
        }
    },

    watch: {
        selected: function() {
            this.$dispatch('updateSelected', this.selected);
        }
    },

})

// parent
var vueApp = new Vue({

    components: {
        child: studentTable
    },

    data: {
        selected: []
    },

    events: {
        updateSelected: function(selected) {
            this.selected = selected;
        }
    },

})
👤haakym

Leave a comment