第一个问题:属性的传递
解决方法:用v-bind="$attrs"
批量属性传值的方法,学过react的都知道,类似于{…props}批量传值。有的属性可能需要二次处理,可以使用props
接收,props
过来的属性,不会出现在$attrs
里了。你可以单独处理后再放回elementui的原生组件里了
// MyInput.vue
<template class="my-input">
<el-input v-bind="$attrs"></el-input>
</template>
<style scoped>
.my-input{
transition:0.3s;
}
.my-input:hover,
.my-input:focus-within{
filter:drop-shadow(0 0 3px raba())
}
</style>
// App.vue
<template>
<div>
<MyInput v-model="data"></MyInput>
</div>
</template>
<script setup>
import MyInput from './components/MyInput.vue'
const data = ref("")
</script>
第二个问题:插槽的传递
解决方法:用$slots
批量传递插槽,同时要考虑作用域插槽的传递
// MyInput.vue
<template class="my-input">
<el-input v-bind="$attrs">
<template v-for="(value,name) in $slots" #[name]="slotData"> // 这里的slotData是el-input组件提供的数据
<slot :name="name" v-bind="slotData || {}"></slot>
</template>
</el-input>
</template>
<style scoped>
.my-input{
transition:0.3s;
}
.my-input:hover,
.my-input:focus-within{
filter:drop-shadow(0 0 3px raba())
}
</style>
// App.vue
<template>
<div>
<MyInput v-model="data">
<template #prepend>
<el-select placeholder="Select" style="width:115px">
<el-option label="Key1" value="1" />
<el-option label="Key2" value="2" />
</el-select>
</template>
<template #append>
<el-button :icon="Search">
</template>
</MyInput>
</div>
</template>
<script setup>
import MyInput from './components/MyInput.vue'
const data = ref("")
</script>
第三个问题:ref引用的问题
解决方法:将子组件的方法给绑定到子组件的实例上,然后获取子组件的实例就可,注意组合式和声明写法是有区别的
<template class="my-input">
<el-input ref="inp" v-bind="$attrs"></el-input>
</template>
<script>
// 声明式写法
export default {
mounted(){
const entries = Object.entries(this.$refs.inp)
for(const [key,value] of entries){
this[key] = value;
}
}
}
</script>
<script setup>
// 组合式写法
const exposeMethods = {}
const entries = Object.entries(this.$refs.inp)
for(const [key,value] of entries){
exposeMethods[key] = value;
}
defineExpose(exposeMethods)
</script>
<style scoped>
.my-input{
transition:0.3s;
}
.my-input:hover,
.my-input:focus-within{
filter:drop-shadow(0 0 3px raba())
}
</style>
// App.vue
<template>
<div>
// 暴漏的是MyInput组件的实例对象
<MyInput v-model="data" ref="inputRef"></MyInput>
</div>
</template>
<script setup>
import MyInput from './components/MyInput.vue'
const data = ref("")
const inputRef = ref(null)
</script>