'Updating data on child components from a parent component in Vue 3

I'm migrating an application from KnockoutJS to VueJS. I'm having difficulty translating a template to a component. It's similar to a tab structure where only 1 item can be active which was controlled using an observable called isActive that I've changed to a ref. When a user clicks on an item I want to loop through the child components in a list on the parent and set the isActive value to false before setting isActive on the clicked item to true.

I have been able to update the clicked item's isActive value but I can't see the isActive ref values on the parent. How can I get the child components and their data from the parent?

I have an example of what the code looks like here. DEMO



Solution 1:[1]

You can use ref to access the child component in the parent:

<template>
    <div>
        <child-component ref="mychild" />
    </div>
</template>

<script>
export default {
    mounted() {
        // this.$refs.mychild will be the instance of the child component.
        // You can access all of its data and methods
    }
}
</script>

Similarly, in the child component you may access the parent component using $parent. This isn't particularly recommended though as it couples the child component to the parent (meaning, it won't really work properly without it, and the goal should usually be to create agnostic components that can be reused anywhere), and usually there will be a better solution possible using props and emitting events.

Solution 2:[2]

If you console out menuItem.isActive.value in our changeSelectionWizardView function you will find your isActive reactive value.

But as I can see from your code you pass a plain/unreactive object as a props to your SelectionMenuItem components. So when you update the isActive value in the parent component the child will not get the change.

One possible solution is, make the menuItems a reactive data. Then pass the reactive menuItem as a props to the child components. And after each change emit event call you just update the menuItems isActive value and then the props will reactively pass the latest updated data to the child components.

I have made some changes in your code, Now I think it's working like what you mentioned in your question above.Here is the link

Lastly, one small suggestion, try to use either option API or composition API, don't use both of them at the same time, It makes your code debugging harder.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Brother Woodrow
Solution 2 nur_riyad