Code snippet background
Here is a typical Vue 3 component (), it references the operation subcomponent through templates
BabylonScene
:
<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 citations:
ref
is a responsive API of Vue 3, used to create a wrapper object, which.value
The attribute points to the internal value. This is used to store subcomponent instances.Initial value:
null
Indicates 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 importedBabylonScene
The type of component (essentially the constructor type of component).
AssumptionBabylonScene
is a class component,typeof
Its constructor type will be returned.InstanceType<T>
TypeScript built-in tool type, used to extract constructorsT
instance 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.value
Runtime error.
Overall meaning
This line of code creates aType-safe responsive references, used for storageBabylonScene
Instance of the component. It explicitly constrains two possibilities:
When the subcomponent is mounted:
for
BabylonScene
Examples.When the initial or child component is not mounted:
for
null
。
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) => { if () { (weatherName); // Type-safe method calls } };
The premise isBabylonScene
Component passdefineExpose
ExposedsetWeather
method.
Associations in templates
<template> <BabylonScene ref="babylonScene" /> </template>
Naming consistency: in the template
ref
Attribute 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 or
class
Grammar definition,InstanceType
Can be used directly.Composition API Components: If subcomponents are used
defineComponent
Definition,InstanceType
Still applicable, because Vue will be processed internally as constructor type.
2. Life cycle timing
Avoid premature visits:exist
onMounted
Before the life cycle,Possibly for
null
, short value check is required before operation.Asynchronous scenarios: If the child component is rendered dynamically (such as through
v-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:
Type safety: Identify the type of subcomponent instances to avoid the risk of spelling errors or methods not present.
Responsive management: Use Vue's responsive system to automatically track instance changes.
Null value protection: Force developers to deal with possible tasks through joint types
null
state.
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!