skip to Main Content

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


  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.

    Login or Signup to reply.
  2. 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

    Login or Signup to reply.
  3. 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>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search