记录解决vue+ts父组件使用$refs调用子组件方法

  1. 创建子组件
<template>
	<div>
	</div>
</template>
<script lang="ts">
import { Component, Vue, Watch, Prop, Emit } from "vue-property-decorator";
@Component({})
export default class Child extends Vue {
	private flag = false;
	public cutFlag(){
		this.flag = true;
	}
}
</script>
  1. 父组件引入子组件
<Child ref="child"></Child>

<script lang="ts">
import { Component, Vue, Watch, Prop, Emit } from "vue-property-decorator";
import Child from "./child.vue";
@Component({
	components:{
		Child
	}
})
export default class Parent extends Vue {
	public mounted() {
		(this.$refs["child"] as Child).cutFlag();
	}
}
</script>

!!!注意子组件暴露的方法用public方式创建

  • 3
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
Vue3 中,你可以通过 `ref` 和 `setup` 函数来获取组件实例,并且调用方法。 假设你有一个组件 `Parent` 和一个组件 `Child`,需要在组件调用 `Child` 组件方法,可以按照以下步骤进行: 1. 在组件中,使用 `ref` 创建一个引用: ```vue <template> <div>组件</div> </template> <script lang="ts"> import { defineComponent, ref } from 'vue'; export default defineComponent({ setup() { const childRef = ref(null); const childMethod = () => { console.log('组件方法调用了'); }; return { childRef, childMethod, }; }, }); </script> ``` 在 `setup` 函数中,我们创建了一个名为 `childRef` 的引用,并将其初始化为 `null`。在 `childMethod` 中,我们定义了一个组件方法,用于在组件调用。 2. 在组件中,使用 `ref` 创建一个引用,并在 `onMounted` 生命周期钩函数中通过 `childRef.value` 获取组件实例: ```vue <template> <div> <button @click="callChildMethod">调用组件方法</button> <Child ref="childRef"></Child> </div> </template> <script lang="ts"> import { defineComponent, onMounted, ref } from 'vue'; import Child from './Child.vue'; export default defineComponent({ components: { Child, }, setup() { const childRef = ref(null); const callChildMethod = () => { if (childRef.value) { childRef.value.childMethod(); } }; onMounted(() => { childRef.value = childRef.value.$refs.child; }); return { childRef, callChildMethod, }; }, }); </script> ``` 在 `setup` 函数中,我们创建了一个名为 `childRef` 的引用,并将其初始化为 `null`。在 `callChildMethod` 中,我们通过 `childRef.value` 获取组件实例,并调用其 `childMethod` 方法。在 `onMounted` 生命周期钩函数中,我们通过 `childRef.value.$refs.child` 获取组件实例,并将其存储在 `childRef.value` 中。 注意,我们在组件模板中使用了 `Child` 组件,并将其通过 `ref` 绑定到了 `childRef` 引用上。在 `onMounted` 生命周期钩函数中,我们可以通过 `childRef.value.$refs.child` 获取到组件实例。这里的 `child` 是组件模板中的 `ref` 名称,用于获取组件实例。 这样,就可以在组件调用组件方法了。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值