組件上的一些屬性沒有在prop:中定義。
因為顯式定義的 prop 適用於向一個子組件傳入信息,然而組件庫的作者並不總能預見組件會被用於怎樣的場景。這也是為什么組件可以接受任意的特性,而這些特性會被添加到這個組件的根元素上。
如果你不希望組件的根元素繼承特性,你可以設置在組件的選項中設置 inheritAttrs: false;
有了 inheritAttrs: false
和 $attrs
,你就可以手動決定這些特性會被賦予哪個元素。
兩者配合使用 要個那個元素加上
v-bind="$attrs",那么這個屬性就會定義到這個元素上,但是class和style屬性仍會在子組件的根節點上
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>非prop得特性</title> </head> <body> <div id="app"> <base-input v-model="username" class="username-input" style="height: 25px;font-size: 20px" label="姓名" placeholder="Enter your username" placeholder2="Enter your username" ></base-input> </div> <script src="https://cdn.jsdelivr.net/npm/vue"></script> <script> Vue.component('base-input', { inheritAttrs: false, props: ['label', 'value'], template: ` <label> {{ label }} <input v-bind="$attrs" v-bind:value="value" v-on:input="$emit('input', $event.target.value)" > </label> ` }) var vm = new Vue({ el: '#app', data:{ username:'', } }) </script> </body> </html>
最終渲染結果