Translate

Friday 19 January 2024

How do you access parent instance in Vuejs explain with example?100

 How do you access parent instance in Vuejs explain with example?


While directly accessing the parent instance is possible using $parent, it's generally discouraged due to potential tight coupling and maintainability issues. Here are preferred approaches:

1. Props and Events:

  • Pass data from parent to child via props:


Code snippet

// Parent component
<template>
  <child-component :data-from-parent="parentData"></child-component>
</template>

// Child component
<template>
  <p>Data from parent: {{ dataFromParent }}</p>
</template>

  • Emit events from child to parent:


Code snippet

// Child component
<template>
  <button @click="$emit('child-event', childData)">Emit Event</button>
</template>

// Parent component
<template>
  <child-component @child-event="handleChildEvent"></child-component>
</template>

2. Provide/Inject (Vue 3):

  • Pass data down through component tree without relying on direct parent-child relationships:


Code snippet

// Parent component
<template>
  <provide :data="providedData"></provide>
  <child-component></child-component>
</template>

// Child component (can be nested deeper)
<script setup>
const providedData = inject('data');
</script>

3. Event Bus (for complex communication patterns):

  • Create a global event bus using a Vue instance:


Code snippet

// Event bus instance
const eventBus = new Vue();

// Child component A
eventBus.$emit('global-event', data);

// Child component B (can be unrelated)
eventBus.$on('global-event', handleEvent);

Key Considerations:

  • Favor props and events: Maintain clear component boundaries and unidirectional data flow.

  • **Use provide/inject for non-hierarchical communication or passing shared data across multiple components.

  • Use event bus judiciously: It can introduce global state and make code harder to reason about.

  • Avoid direct $parent access: It can lead to tight coupling and make code less maintainable.

Additional Considerations:

  • Vuex: For large-scale applications, consider Vuex for centralized state management and more structured communication patterns.

No comments:

Post a Comment

Note: only a member of this blog may post a comment.