Vue.js component communication

How to make components communicate in a Vue.js application.


Components in Vue can communicate in various ways.

Props

The first method is to useProps.

The parent "passes" data by adding parameters to the component declaration:

<template>
  <div>
    <Car color="green" />
  </div>
</template>

<script> import Car from ‘./components/Car’

export default { name: ‘App’, components: { Car } } </script>

Props are one-way: from parent to child. Every time the parent changes the prop, the new value will be sent to the child and re-rendered.

The opposite is not true. You should never mutate props inside sub-components.

Use events to communicate with parents from children

Through events, you can communicate from children to parents:

<script>
export default {
  name: 'Car',
  methods: {
    handleClick: function() {
      this.$emit('clickedSomething')
    }
  }
}
</script>

Parents can usev-onWhen the directive is included in the component in its template:

<template>
  <div>
    <Car v-on:clickedSomething="handleClickInParent" />
    <!-- or -->
    <Car @clickedSomething="handleClickInParent" />
  </div>
</template>

<script> export default { name: ‘App’, methods: { handleClickInParent: function() { //… } } } </script>

You can of course pass parameters:

<script>
export default {
  name: 'Car',
  methods: {
    handleClick: function() {
      this.$emit('clickedSomething', param1, param2)
    }
  }
}
</script>

And retrieve them from the parent:

<template>
  <div>
    <Car v-on:clickedSomething="handleClickInParent" />
    <!-- or -->
    <Car @clickedSomething="handleClickInParent" />
  </div>
</template>

<script> export default { name: ‘App’, methods: { handleClickInParent: function(param1, param2) { //… } } } </script>

Use event bus to communicate between any components

Using events, you are not limited to the relationship between children and parents.

You can use the so-calledActivity bus.

We used abovethis.$emitEmit an event on the component instance.

Instead, what we can do is emit events on more accessible components.

this.$rootThe root component is usually used for this purpose.

You can also create a Vue component dedicated to this job, and then import it to the desired location.

<script>
export default {
  name: 'Car',
  methods: {
    handleClick: function() {
      this.$root.$emit('clickedSomething')
    }
  }
}
</script>

Any other component can listen to this event. You canmountedcall back:

<script>
export default {
  name: 'App',
  mounted() {
    this.$root.$on('clickedSomething', () => {
      //...
    })
  }
}
</script>

Alternatives

This is what Vue does out of the box.

When you exceed this range, you can viewWicksOr other third-party libraries.

Download mine for freeVue manual


More vue tutorials: