vue3中父组件拿到子组件的dom实例

当我们对UI组件进行二次封装的时候,我们通常会用到UI组件的实例方法,这个时候我们就需要在父组件中拿到子组建中UI组件的实例,获取子组件dom有两种情况
不使用setup语法糖的情况
这中情况下我们可以使用this,可以将UI组件的实例直接挂到当前组件实例上,具体代码如下

<template>
	<div >
		<el-input ref="inpRef"  v-model="input" placeholder="Please input" />
	</div>
</template>
<script>
	export default{
		mounted() {
			const entries = Object.entries(this.$refs.inpRef)
			for( const [key,value] of entries){
				this[key] = value
			}
		}
	}
</script>
父组件调用
<template>
  <input-my ref="myRefInput"></input-my>
</template>
<script setup>
const myRefInput = ref()
onMounted(()=>{
	myRefInput.value.focus()
})
</script>

使用setup的情况下
这个时候我们无法使用this,注意在setup中setup是封闭的,不会将子组件事件暴露出来,所以要用defineExpose(),将需要在父组件调用的函数暴露出去,子组件代码如下

<template>
	<div >
		<el-input ref="inpRef"  v-model="input" placeholder="Please input" />
	</div>
</template>
<script lang="ts" setup>
	import { ref,onMounted } from 'vue'
	const input = ref('');
	const inpRef = ref();
	function getDom(){
		return inpRef.value
	}
	defineExpose({
	    getDom,
	})

</script>

父组件调用

<template>
  <input-my ref="myRefInput"></input-my>
</template>
<script setup>
const myRefInput = ref()
onMounted(()=>{
	myRefInput.value.getDom().input.focus()
})
</script>
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值