vue3 ts获取组件 ref元素的值

在 Vue 3 + TypeScript 中,要获取组件 ref 元素的值,可以通过 ref 函数创建一个 ref,并将其绑定到组件的 ref 属性上。然后,可以通过访问 ref 的 .value 属性来获取该组件的实例。

以下是一个示例代码:

<template>
  <div>
    <ChildComponent ref="childComponentRef" />
    <button @click="getRefValue">获取组件的值</button>
  </div>
</template>

<script lang="ts">
import { ref } from 'vue';
import { defineComponent, Ref } from 'vue';

import ChildComponent from './ChildComponent.vue';

export default defineComponent({
  components: {
    ChildComponent
  },
  setup() {
    const childComponentRef: Ref<any> = ref(null);

    const getRefValue = () => {
      const childComponentInstance = childComponentRef.value;
      if (childComponentInstance) {
        const value = childComponentInstance.getValue();
        console.log(value);
      }
    };

    return {
      childComponentRef,
      getRefValue
    };
  }
});
</script>

在上述代码中,我们首先使用 ref 函数创建了一个名为 childComponentRef 的 ref,并将其绑定到 ChildComponent 组件的 ref 属性上。然后,在 getRefValue 方法中,通过访问 childComponentRef.value,我们可以获取到 ChildComponent 组件的实例。然后,我们可以调用组件的方法或访问组件的属性。

需要确保 ChildComponent.vue 文件中的组件有定义 getValue() 方法或对应的需要获取的属性。

请注意,在 TypeScript 中,为了类型安全,我们将 childComponentRef 声明为 Ref<any> 类型。如果你知道 ChildComponent 的具体类型,可以将其替换为正确的类型。

猜你喜欢

转载自blog.csdn.net/qq_43784821/article/details/130706956