Home » vue » $.parent vs emitting and listening events performance comparison

$.parent vs emitting and listening events performance comparison

Posted by: admin November 26, 2021 Leave a comment

Questions:

Suppose I am importing component B, which fires a method defined in the parent component A

Component B:

....,
methods: {
    onSomeEvent: function() {
        this.$parent.doSomething();
    }
},
....

Component A:

import ComponentB from 'componentB.vue'
....,
methods: {
    doSomething: function() {
        console.log('Something done by the parent');
    }
},
....

The other way to achieve the same effect would be to emit event in Component B and then listening to it in Component A:

Component B:

....,
methods: {
    onSomeEvent: function() {
        this.$emit('eventForParent');
    }
},
....

Component A:

....
<ComponentB @eventForParent="doSomething()" />
....

import ComponentB from 'componentB.vue'

....,
methods: {
    doSomething: function() {
        console.log('Something done by the parent');
    }
},
....

The first approach has a draw back, it only works if B is the direct child of A while the second approach works with indirect imports as well. But does it come at a cost if we are talking about a complex UI/UX design?

Is the first approach faster than second one? Any help would be appreciated?

Answers:

This question is bound to be flagged as being open to opinion. However – I’ll do my best to answer:

In short – it really depends on your use case.
If you’re building a component that you will re-use throughout your project, or in other projects (say for example, a simple datepicker), it would be best to take the route of passing properties and emitting events. Doing so gives the flexibility of not relying on what methods are available in it’s parent component.

However, if your component is only being used in one specific place – then it might be OK to go down the route of using Vue.$parent(). However – you should consider whether having logic in your parent component is necessary, if it will only be used to control the child component. So even in this case, using events and properties would possibly be the better option.

One case where using Vue.$parent() is very useful, and suitable – is when you have a component nested through <router-view>. Passing properties and setting up events in this case wouldn’t be suitable – so, if there is a method in the parent component that you needed to access – Vue.$parent() would be a good solution here.