So I want to achieve what the title says. Let’s say I have this structure:
parent -> child -> secondChild
Now, I have a variable in the parent called isActive
for example. I know I can do it like this:
parent.vue
<child :active="isActive" />
child.vue
<template>
<secondChild :active="props.active"
</template>
<script setup>
const props = defineProps(['active'])
</script>
secondChild.vue
<template>
{{isActive}}
</template>
<script setup>
const props = defineProps(['active'])
</script>
So this can work yeah. But this wont be nice if I have 10 components nested in each other. How could I do this good without using pinia
or vuex
Thanks
3
Answers
You can write your own Vue 3 State Management file.
Then in any component, you can import it and use it like the following.
Note that the variable is going to be reactive in all of them since we are setting it through
ref
…and you can also usereactive
,computed
and so on here):Although this works, it is very important to state that in a scenario where this would be shared by 10+ components, the best approach indeed would be to use Pinia.
It seems to me that you need something like React’s Context API to avoid prop drilling. You can use the Provide/Inject option. You can import
provide
fromvue
and use it in your ancestor component for defining your data and useinject
to inject that data into your child component. The schema of your parent component may look like this:which in every
ChildComponent
you can have another component that needs that dataFor this you use
provide/inject
:https://vuejs.org/guide/components/provide-inject.html
secondChild.vue