Przemek
Przemek

Reputation: 822

Vue pass data from child component to child component

So I have a structure like this

<Root>
<HomeNav> router-view
<RouterLink>
<RouterLink>
<RouterLink>
<RouterLink>
<RouterLink>
<Home> router-view
<RouterLink> 

Now, each of HomeNav router links is changing the data in component by passing data to root, however that means that I need to bind that data:

      <router-view v-bind:title="title" v-bind:text="text" v-bind:youtube="youtube" v-bind:transition="transition"></router-view>

and run the functions on created and updated:

new Vue({
  el: '#app',
  router,
  data: Variables,
  created: function () {
    path = pathname.pathname();
    pathLenght = pathname.countPathLenght(path);
    this.homeText(this.data);
  },
  updated: function () {
    path = pathname.pathname();
    pathLenght = pathname.countPathLenght(path);
    Pace.restart()
    this.homeText(this.data);
  },
  methods: {
    homeText(data) {
      data = toogleData.checkText(data);
      this.title = data[0];
      this.text = data[1];
      this.youtube = data[2];
    }
  }
})

However, the problem is I don't need that data on all of the routes and I don't need to trigger this.homeText function or bind that specific data on every single root. It is only needed on homepage, so the first route.

So the question is, is it possible to directly pass data from HomeNav component to Home component without having all that code in global (root) component?

Upvotes: 0

Views: 228

Answers (1)

Justin MacArthur
Justin MacArthur

Reputation: 4050

This is a great place for the MessagePump that the VueJs documentation proposes. It is in essence and unbound Vue object that acts as an intermediary between objects. This allows you to define and call events on the pump which gets passed to the appropriate component.

window.MessagePump = new Vue({});

Vue.Component(
    'HomeNav',
    {
        ...
        data: function () {
            return {
                homeText: 'something'
            }
        },
        ...
        mounted: function () {
            var thisArg = this
            MessagePump.$on(
                'homeTextChanged',
                function(newText) {
                    thisArg.homeText = newText;
                }
            );
        }
        ...
    }
);

Vue.Component(
    'Home',
    {
        ...
        mounted: function () {
            MessagePump.$emit('homeTextChanged', 'To This');
        }
        ...
    }
);

This will trigger the event and the changing of homeText from 'something' to 'To This'.

Upvotes: 1

Related Questions