记VUE3+TS 获取组件类型的方法踩坑

获取组件类型的方法

    const AccountRef = ref<InstanceType<typeof LoginAccount>>()

遇到的坑:typeof LoginAccount一直报红线提示错误

LoginAction: () => vo...' provides no match for the signature 'new (...args: any): any'.

问题原因:

使用的是webstorm codeing,通过webstorm自带右键新建vue文件,创建出来的文件是不带defineComponent的,所以导致上述的一直报红线

<script lang="ts">
export default {

}
</script>

解决办法:引用defineComponent

<script lang="ts">
import { defineComponent } from 'vue'
export default defineComponent({//注意这里的这个小括号不能漏

})
</script>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
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 官方文档。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值