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
的使用。