vue3 + ts 获取组件 ref 实例

vue3 + ts 获取组件 ref 实例

使用 vue3 和 ts 时,为了获取 组件 ref 实例,就需要在 ref 函数的泛型中指定类型。如何获取组件的类型呢?
vue 官方文档中 TypeScript 支持里已经告诉我们了一个获取组件类型的方法,InstanceType<typeof 组件名称>,使用方式如下:

const $userForm = ref<InstanceType<typeof userForm>>();
  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
Vue3中使用TypeScript获取动态组件component实例调用里面组件的方法,可以先通过 `ref` 获取动态组件实例,再通过 `as` 关键字将其转换为具体的子组件类型,从而调用子组件中的方法。 例如,假设有一个动态组件 `MyComponent`,其中包含了一个子组件 `ChildComponent`,并且我们需要在父组件获取 `ChildComponent` 实例并调用其方法。可以使用如下代码: ```vue <template> <div> <component :is="selectedComponent" ref="myComponent"></component> <button @click="handleClick">Call Child's Method</button> </div> </template> <script lang="ts"> import { defineComponent, ref } from 'vue' import ChildComponent from './ChildComponent.vue' export default defineComponent({ components: { ChildComponent }, data() { return { selectedComponent: 'ChildComponent' } }, setup() { const myComponentRef = ref<MyComponent | null>(null) const handleClick = () => { const childComponent = myComponentRef.value?.$refs.child as ChildComponent if (childComponent) { childComponent.doSomething() } } return { myComponentRef, handleClick } } }) </script> ``` 在上面的代码中,我们使用 `ref` 将动态组件 `MyComponent` 的实例绑定到 `myComponentRef` 变量上,并使用 `as` 关键字将其类型转换为 `MyComponent | null`。然后,在 `handleClick` 方法中,我们通过 `myComponentRef.value?.$refs.child` 获取到子组件 `ChildComponent` 的实例,并将其类型转换为 `ChildComponent`。最后,我们就可以调用 `ChildComponent` 中的方法了。 需要注意的是,在模板中使用 `ref` 时,需要添加一个 `.value` 后缀来访问 `ref` 变量所引用的对象。例如,上面的代码中,我们通过 `myComponentRef.value?.$refs.child` 来获取组件 `ChildComponent` 的实例。 另外,如果子组件中的方法需要访问子组件的数据或者方法,可以使用 `provide` 和 `inject` 方法来实现。具体使用方法可以参考 Vue3 官方文档。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值