封装ant组件-组件实现继承ant组件原有的属性-事件-插槽-作用域插槽-实例
解释一下:
需要达到的效果就是,比如我封装一个a-input,需要达到的效果是:在使用封装好的组件时候,能够继承原来ant组件的a-input的所有属性、事件、插槽、作用域插槽、实例。
这个就了不得了!!!在实际开发中,我们遇到这样的需求的时候,不可能去一个一个属性的写props吧,一个一个的去写事件,这样就。。。。。
进入正题。
需要用到的关键知识:
vue的几个属性:
1.拿到父组件传递的自定义属性:
this.$attrs
2.拿到父组件传递的插槽:
this.$slots
3.拿到父组件传递的事件
this.$listeners
下面是封装a-input的一个示例:
<template>
<a-input v-bind="$attrs" ref="ipt">
<template v-for="(value,name) in $slots" #[name]="slotData">
<slot :name="name" v-bind="slotData"></slot>
</template>
</a-input>
</template>
<script>
export default {
props: {
icon: {
type: String,
default: ''
}
},
mounted() {
// 1.属性
// console.log(this.$attrs)
// 2.插槽
// console.log(this.$slots)
// 3.作用域插槽
// <slot :name="name" v-bind="slotData"></slot>
// 4.事件
// for (let key in this.$listeners) {
// this.$refs.ipt[key] = e => {
// this.$emit(key, e)
// }
// }
// 5.实例
// console.log(this.$refs.ipt)
// let refsObj = Object.entries(this.$refs.ipt)
// refsObj.forEach(([key, value]) => {
// if (typeof value === 'function') {
// this[key] = value
// }
// });
}
}
</script>
<!-- 在父组件中的用法 -->
<!--
<MyInput ref="ipt" :maxLength="5" :v-model="222" placeholder="input with clear icon" icon="eye"
@onChange="changeHandle" @onChange1="changeHandle">
<a-icon slot="prefix" type="user" :slotData="{name:'liu'}" />
</MyInput>
-->