一、需求
二次封装elemtnui组件的文本框,供我们项目使用
二、实现
子组件实现(MyInput.vue);
<template>
<el-input ref="childRef" v-bind="$attrs"></el-input>
</template>
<script lang="ts" setup>
import { onMounted, reactive, ref } from 'vue';
/*
defineOptions参考插件 https://vue-macros.sxzz.moe/macros/define-options.html
或者参考官网对setup中设置name的解释 https://cn.vuejs.org/api/options-misc.html#name
*/
defineOptions({
name: 'myInput'
});
const childRef = ref();
const options = reactive<{[K: string]: any}>({});
onMounted(() => {
const entries = Object.entries(childRef.value);
for(let [key, value] of entries){
if(!value || typeof value !== 'function'){
continue;
}
options[key] = value;
}
});
defineExpose(options);
</script>
父组件实现
<template>
<myInput ref="myInputRef" v-model="val" />
</template>
<script lang="ts" setup>
import { onMounted, ref } from 'vue';
import myInput from '@com/myInput/index.vue';
defineOptions({
name: 'xxx'
});
const myInputRef = ref();
const val = ref(0);
onMounted(() => {
console.log(myInputRef.value); // 这里的就是el-input组件给我们提供的所有方法
});
</script>