组件属性与事件透传以及实例
当我们想二次封装一个 ui 组件来适应项目需求时,组件的属性往往很多,如果一个一个绑定麻烦而且不容易维护 这时候就可以使属性和事件透传。
# 绑定语法v-bind
- 一般通过缩写为
:使用,动态绑定某个值。但如果使用v-bind="$attrs"来使用$attrs的每一个属性与值都会解构成为当前组件的一个属性与值
<a-input v-bind="{placeholder:'请输入内容'}" />
// 相当于下面的写法
<a-input placeholder="请输入内容"> </a-input>
# 绑定事件 v-on
- 与属性类型,事件也是如此
<a-input v-on="{click:this.myClick}" />
// 相当于下面的写法
<a-input @click="myClick"> </a-input>
...
methods:{
myClick(){}
}
# 能做些什么? config 表单
在项目中,一个表单,既要通过栅格进行布局,又要包裹 form-item,其中的显示隐藏逻辑与事件都在一个组件中,页面的行数有时候甚至达到上千行,及其难维护。
通过使用属性以及事件透传,通过内置组件
component来决定要渲染哪个组件,使用 config 来渲染一个表单将变得非常容易
template 看起来是这样的
<template>
<a-spin :spinning="loading">
<a-form ref="FormRef" :form="form">
<a-row>
<a-col v-for="item in config" :key="item.key" :span="item.hidden ? 0 : item.span || 12">
<a-form-item v-if="!item.hidden" :label="item.label" v-bind="item.itemProps"> //form-item的属性透传
<slot v-if="item.component === 'slot'" :name="item.slotName" /> //特殊清空,使用插槽插入
<div v-else-if="item.component === 'innerText'">{{item.Conent}}</div> //我就想渲染一段文字到表单项目上
<!-- 自定义组件渲染 -->
<template v-else>
<component
:is="item.component" //渲染item.component的值的组件
v-bind="item.props"
v-decorator="item.decorator"
v-on="item.listeners"
></component>
</template>
</a-form-item>
</a-col>
</a-row>
</a-form>
</a-spin>
</template>
props:{
config: {
type: Array,
default: () => [],
},
}
// 要传入的config配置
config: [
{
key: '', // forin循环时绑定的key
component: '', //渲染类型 slot时需设置slotName并插入,innerText时渲染文本
slotName: '', //使用插槽时的插槽名
hidden: false, //是否隐藏
span: 6, //col的span
Conent:"",
label: '', //form label
decorator: ['couponIds', { rules: [{ required: true, message: '请选择' }] }], //插入的表单绑定验证项
props: {}, //注入到当前表单组件的属性
listeners:{} //注入到当前表单项目的事件
},
],
通过上面的封装,表单的显示逻辑被封装到一个组件里,我们便可以专注于维护一个 config,在当前组件处理事件与逻辑
编辑 (opens new window)
上次更新: 2022/05/28, 10:34:23