SoFunction
Updated on 2025-04-13

Sample code for secure access to child components in Vue3

Code snippet background

Here is a typical Vue 3 component (), it references the operation subcomponent through templatesBabylonScene

<template>
  <BabylonScene ref="babylonScene" />
</template>
 
<script setup lang="ts">
import BabylonScene from './components/';
import { ref } from 'vue';
 
const babylonScene = ref<InstanceType<typeof BabylonScene> | null>(null);
 
const setWeather = (weatherName: string) => {
  if () {
    (weatherName);
  }
};
 
defineExpose({ setWeather });
</script>

The most critical code is:

const babylonScene = ref<InstanceType<typeof BabylonScene> | null>(null);

This article will interpret this line around this article.

Layer-by-layer analysis

1. The role of ref

  • Responsive citationsrefis a responsive API of Vue 3, used to create a wrapper object, which.valueThe attribute points to the internal value. This is used to store subcomponent instances.

  • Initial valuenullIndicates that the initial reference is empty. When the child component is mounted, Vue will automatically assign the instance to

2. The mystery of type annotation

InstanceType<typeof BabylonScene> | null

In the parent component, the method exposed by the child component can be called directly by reference:

Practical application scenarios

Calling child component method

  • typeof BabylonScene
    Get importedBabylonSceneThe type of component (essentially the constructor type of component).
    AssumptionBabylonSceneis a class component,typeofIts constructor type will be returned.

  • InstanceType<T>
    TypeScript built-in tool type, used to extract constructorsTinstance type. For example:

class MyComponent {}
type ComponentInstance = InstanceType<typeof MyComponent>; // = MyComponent
  • Joint Type| null
    It means that the reference may benull(Initial status or component not mounted), avoid direct access.valueRuntime error.

Overall meaning

This line of code creates aType-safe responsive references, used for storageBabylonSceneInstance of the component. It explicitly constrains two possibilities:

  • When the subcomponent is mounted:forBabylonSceneExamples.

  • When the initial or child component is not mounted:fornull

Practical application scenarios

Calling child component method

In the parent component, the method exposed by the child component can be called directly by reference:

const setWeather = (weatherName: string) =&gt; {
  if () {
    (weatherName); // Type-safe method calls  }
};

The premise isBabylonSceneComponent passdefineExposeExposedsetWeathermethod.

Associations in templates

<template>
  <BabylonScene ref="babylonScene" />
</template>
  • Naming consistency: in the templaterefAttribute value ("babylonScene") Must be consistent with the variable name in the script, Vue will automatically establish an association.

  • Automatic mount: The child component instance will be automatically assigned to

Things to note

1. Component type issues

  • Class Components: If the child component uses the Options API orclassGrammar definition,InstanceTypeCan be used directly.

  • Composition API Components: If subcomponents are useddefineComponentDefinition,InstanceTypeStill applicable, because Vue will be processed internally as constructor type.

2. Life cycle timing

  • Avoid premature visits:existonMountedBefore the life cycle,Possibly fornull, short value check is required before operation.

  • Asynchronous scenarios: If the child component is rendered dynamically (such as throughv-if), make sure that the child component is accessed again when its reference exists.

3. Type extension

If a child component exposes a method or property of complex types, the TypeScript interface can be defined in the child component and exported for use by the parent component:

// 
export interface BabylonSceneMethods {
  setWeather: (name: string) => void;
}
 
defineExpose<BabylonSceneMethods>({
  setWeather: (name) => { /* ... */ }
});

The interface type can be used directly when referring to the parent component:

const babylonScene = ref<BabylonSceneMethods | null>(null);

Summarize

passref<InstanceType<typeof Component> | null>We implemented the model:

  1. Type safety: Identify the type of subcomponent instances to avoid the risk of spelling errors or methods not present.

  2. Responsive management: Use Vue's responsive system to automatically track instance changes.

  3. Null value protection: Force developers to deal with possible tasks through joint typesnullstate.

This pattern is very practical when it is necessary to directly manipulate subcomponents (such as calling methods, accessing DOM elements), especially in complex component libraries or graphics rendering (such as ) scenarios, which can significantly improve the robustness and maintainability of the code.

The above is the detailed content of the sample code for safe access to subcomponents in Vue3. For more information about Vue3 secure access to subcomponents, please follow my other related articles!