Vue3 TypeScript 组件 Ref 属性声明及获取实例
Vue3 + TypeScript 组件 Ref 属性声明及获取实例
在 Vue 3 和 TypeScript 中,您可以使用 createRef 函数来声明组件的 ref 属性,并从中获取组件实例。
1. 安装依赖
首先,确保您已经安装了 Vue 3 和 TypeScript 的相关依赖。
2. 声明 Ref 属性
在组件的定义中,使用 createRef 函数来声明 ref 属性。例如:
import { defineComponent, ref, createRef } from 'vue';
export default defineComponent({
setup() {
// 声明一个 ref 属性
const myComponentRef = createRef();
// 获取组件实例
const getComponentInstance = () => {
if (myComponentRef.value) {
console.log(myComponentRef.value);
}
};
return {
myComponentRef,
getComponentInstance
};
}
});
3. 绑定 Ref 属性
在模板中,您可以使用 ref 指令将组件的 ref 属性绑定到具体的元素或组件实例上。例如:
<template>
<div>
<MyComponent ref='myComponentRef'></MyComponent>
<button @click='getComponentInstance'>获取组件实例</button>
</div>
</template>
4. 获取组件实例
通过点击按钮,您可以调用 getComponentInstance 方法,并获取到组件实例。
原文地址: http://www.cveoy.top/t/topic/bqvq 著作权归作者所有。请勿转载和采集!