1
votes

I have a simple component hierarchy, in which there is one parent component, which contains the following template <div><component :is="current"></component></div> and two child components, which are dynamically 'switched' out, via the value of current.

The logic for the 'switching' of components is being handled in the parent component. However, when I try to execute a method in the second child component (in response to an event emitted from the first child component, being listened to in the parent component, and altering the value of current in the parent component) through the mounted lifecycle hook, the expected result is not observed.

Essentially, I cannot find a decent way of invoking a child component's methods when that component is 'switched' in as the current component in the parent component.

I have realistically looked at using the $refs and $childrenproperties on the instance, but these do not seem to be of any assistance. I have also reasoned using the event system. I usually 'define' an event listener in the mounted lifecycle hook, however, I refer to the 'issue' of using the lifecycle hooks

What is the usual approach to this situation?

1

1 Answers

2
votes

There are two options that immediately come to mind for child components invoking methods on being the "current" child component:

1) Using the mounted lifecycle hook. In order for this to work, you must be using v-if in order to conditionally display the child component, otherwise the child component will not trigger the mounted lifecycle hook. Otherwise, if you're using v-show or some other mechanism for conditionally displaying the child component, the mounted hook will only ever trigger once.

2) Using watched properties. In lieu of the above, you could do something like the following:

<child-component :target_prop="current"></child-component>

Vue.component('child-component', {
    . . .,
    props: ['target_prop'],
    watch: {
        target_prop: function() {
            if(this.target_prop == your_expected_value) {
                //execute the desired method for this component
            }
        }
    }
});

This is, of course, just a proof-of-concept example and there are plenty of alternative ways to use the watched properties to your advantage.

I've also heard of using a "bus" to handle inter-component communication, but I don't believe it would be any better than the above two solutions (and is arguably worse).

Personally, I prefer the mounted lifecycle hook approach, though there's the caveat that any "settings" or data in your child components will be lost on switching between them (although you could also emit a settings object on destruction and store/restore those settings as needed, but that could get messy). You'll have to make the final judgment on which approach better suits your needs and which consequences you're more comfortable dealing with.