ui组件二次封装(vue)
组件二次封装的意义
- 保证一个系统中ui风格和功能的一致性
- 便于维护
从属性、事件、插槽、ref这几方面考虑
- 属性和事件的处理:ui组件上绑定$attrs(v-model本质也是一个属性加一个事件,所以也在其列)
在自定义组件中打印$attrs:父组件传递过来的所有属性和事件 - 自定义组件本身定义的属性和事件。
- 插槽的处理:循环$slots设置ui组件插槽,并定义同名自定义组件插槽
在自定义组件中打印$slots:父组件中设置的插槽对象(键值对)
- ref的处理(如果在自定义组件上使用ref,大概率是想用ui组件里的方法)
将ui组件实例的所有属性都放到自定义组件上
完整例子
子组件:
<template><el-input ref="elInput" v-bind="$attrs"><template v-for="(_, name) in $slots" #[name]= "scopeData"><slot :name="name" v-bind="scopeData"></slot></template></el-input>
</template>
mounted() {for (const key in this.$refs.elInput) {this[key] = this.$refs.elInput[key]}
}
----------------------------------------------------
父组件:
<my-input ref="wrapRef" v-model="inputVal" maxlength="5"><template #prefix>prefix</template>
</my-input>
data() {return {inputVal: '123'}
},
mounted() {this.$refs.wrapRef.focus()
}