[Vuejs]-Vue 3 pass props from parent to child of child

1👍

For this you use provide/inject:

https://vuejs.org/guide/components/provide-inject.html

parent.vue

<script setup>
import {provide} from 'vue';

provide('active', isActive);
</script>

<template>
<child />
</template>
child.vue

<template>
<secondChild />
</template>

secondChild.vue


<template>
<secondChild />
</template>


<script setup>

import {inject} from 'vue';

const isActive = inject('active', ref(false));

</script>

1👍

You can write your own Vue 3 State Management file.

// stores/active.js

import { ref } from 'vue'

export const isActive = ref(false)

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 use reactive, computed and so on here):

// component.vue

<script setup>
import { isActive} from '/stores/active'

// isActive.value is reactive
</script>

<template>
 <!-- isActive is reactive -->
 {{ isActive }}
</template>

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.

1👍

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 from vue and use it in your ancestor component for defining your data and use inject to inject that data into your child component. The schema of your parent component may look like this:

<template>
  <Provide>
    <div>
      <ChildComponent />
      <div>
         <AnotherChildComponent />
      </div>
    </div>
  </ProvideUserSettings>
</template>

which in every ChildComponent you can have another component that needs that data

Leave a comment