vue vm.$attrs 使用


1、vm.$attrs 说明

https://cn.vuejs.org/v2/api/#vm-attrs

将父组件的属性(除去在props中传入的属性)传递给子组件。

2、代码分析

以下是element-ui input源码

<input :tabindex="tabindex" v-if="type !== 'textarea'" class="el-input__inner" v-bind="$attrs" :type="type" :disabled="inputDisabled" :readonly="readonly" :autocomplete="autoComplete || autocomplete" :value="currentValue" ref="input" @compositionstart="handleComposition" @compositionupdate="handleComposition" @compositionend="handleComposition" @input="handleInput" @focus="handleFocus" @blur="handleBlur" @change="handleChange" :aria-label="label"
      >

el-input的props源码:

props: { value: [String, Number], size: String, resize: String, form: String, disabled: Boolean, readonly: Boolean, type: { type: String, default: 'text' }, autosize: { type: [Boolean, Object], default: false }, autocomplete: { type: String, default: 'off' }, /** @Deprecated in next major version */ autoComplete: { type: String, validator(val) { process.env.NODE_ENV !== 'production' && console.warn('[Element Warn][Input]\'auto-complete\' property will be deprecated in next major version. please use \'autocomplete\' instead.'); return true; } }, validateEvent: { type: Boolean, default: true }, suffixIcon: String, prefixIcon: String, label: String, clearable: { type: Boolean, default: false }, tabindex: String },

以下是el-input小例子:

<el-input maxlength="5" minlength="2">
</el-input>
<el-input>组件添加了2个原生属性,注意这2个原生属性并没有在prop里面,这2个属性是控制input的最大输入和最小输入长度的,那么这2个属性现在仅仅放在了父元素<el-input>上,如何将其传递给素<el-input>内的原生input子元素呢?不传递则这2个属性不起作用,因为子input上没有这2个属性。答案就是通过v-bind="$attrs"来实现,它将父元素所有非prop的特性都绑定在了子元素input上,否则还得在props里声明maxlength,minlength,代码量增大。
这就是$attrs的使用。


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM