乐闻世界logo
搜索文章和话题

Vue 3 how to get information about $ children

1个答案

1

In Vue 3, due to updates in architecture and design philosophy, the team has decided to no longer directly support the $children property, which was used in Vue 2 to directly access child component instances. This design change aims to encourage developers to adopt more declarative and maintainable coding practices.

However, if you do need to access child component instances in Vue 3, several alternative approaches are available:

1. Using ref and provide/inject

This is the recommended approach in Vue 3 to replace direct use of $children. You can use the provide method in the parent component to expose data or methods, and then use inject in the child component to consume these.

Parent Component:

vue
<script setup> import { provide } from 'vue'; import ChildComponent from './ChildComponent.vue'; provide('getParentData', () => 'This is data from the parent component'); </script> <template> <ChildComponent /> </template>

Child Component:

vue
<script setup> import { inject } from 'vue'; const getParentData = inject('getParentData'); const parentData = getParentData(); </script> <template> <div>{{ parentData }}</div> </template>

2. Using Event Dispatching

If you only need child components to report information to the parent component, custom events provide a clean solution.

Child Component:

vue
<script setup> import { defineEmits } from 'vue'; const emit = defineEmits(['reportToParent']); function report() { emit('reportToParent', 'Child component status'); } </script> <template> <button @click="report">Report to Parent</button> </template>

Parent Component:

vue
<script setup> import ChildComponent from './ChildComponent.vue'; const handleReport = (data) => { console.log('Data received from child component:', data); }; </script> <template> <ChildComponent @report-to-parent="handleReport" /> </template>

By using these methods, you can effectively replace $children usage in Vue 3 while maintaining component decoupling and improved maintainability. For specific scenarios, I can provide more detailed solutions.

2024年11月20日 22:19 回复

你的答案