使用$attrs 和 inheritAttrs提高组件封装的灵活性,快捷绑定多个属性!

$attrs 描述

通过v-bind='$attrs'形式,来获取组件上绑定的所有属性!

inheritAttrs 描述

该属性用来设置组件上绑定的属性是否继承在父级根标签上,组件上绑定的属性默认会绑定在父及根标签上,该属性若设置为false则根级标签不会绑定所属组件传入的属性!

无添加 attrs 和 inheritAttrs 代码示例

1
2
<my-input type="text"></my-input>
<my-input type="password"></my-input>
1
2
3
4
5
6
<!-- input component -->
<template>
<div class="my-input">
<el-input>
</div>
</template>

不使用 $attrsinheritAttrs 效果

添加 attrs 和 inheritAttrs 代码示例

1
2
<my-input v-model="message" type="text"></my-input>
<my-input v-model="message" type="password"></my-input>
1
2
3
4
5
6
7
export default {
data: () {
return {
message: 'Hello 哈默!'
}
}
}
1
2
3
4
5
6
<!-- input component -->
<template>
<div class="my-input">
<el-input v-bind="$attrs" :value="value" @input="@$emit('input')">
</div>
</template>
1
2
3
4
export default{
inheritAttrs: false,
props: ['value']
}

使用 $attrsinheritAttrs 效果