vue3自动暴露element-plus组件的ref
自动暴露子组件的方法,注意在TS下,需要自己声明类型,我这里全用any代替了
<template>
<el-button @click="getFocus">获得焦点</el-button>
<com ref="comRef" />
</template>
<script setup lang="ts">
import { ref } from 'vue'
import com from './components/com.vue'
const comRef = ref(null);
const getFocus = () => {
(comRef.value! as any).focus()
};
</script>
子组件
<template>
<el-input v-model="val" placeholder="请输入文本框" ref="inputRef" />
</template>
<script setup lang="ts">
import { ref } from 'vue'
import { InputInstance } from 'element-plus'
const val = ref('');
const inputRef = ref<null | InputInstance>(null);
defineExpose(new Proxy({}, {
get(_target, key) {
return (inputRef.value as any)?.[key];
},
has(_target, key) {
return key in inputRef.value! as any;
},
}))
</script>