禁用特性继承
inheritAttrs: false;
如果你不希望组件的根元素继承特性,你可以在组件的选项中设置
这尤其适合配合实例的 $attrs 属性使用,该属性包含了传递给一个组件的特性名和特性值
以上是官网的解释。
经过摸索得到了一下的理解。
1、inheritAttrs默认为true;即允许继承的意思。
2、$attrs为组件标签内没有在组件内用props声明的属性(除style和class外)。
<div id="app" style="font-size: 24px;">
<base-input
v-model="username"
v-bind:class="label"
v-bind:style="{fontSize:post.likes+'px'}"
v-bind:a='a'
add="ssss"
placeholder="Enter you"
></base-input>
</div>
//此时的$attrs包括属性:a、placeholder、add
组件为
template: `<label >
<p v-bind="$attrs"> {{ label }}</p>
<input v-bind="$attrs" v-bind:value="value"
v-on:input="$emit('input', $event.target.value)">
</label>`
如果在组件内添加:
inheritAttrs: false
```则渲染的元素为
![红色部分为$attrs所代表的未注册的属性,黄色为class和style。](https://img-blog.csdnimg.cn/20181128152939892.jpg?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dhbmd4aWFveGlhb3Nlbg==,size_16,color_FFFFFF,t_70)
即$attrs添加在哪一个标签上,哪一个标签上就会被渲染出这些属性
如果在组件内去掉:
inheritAttrs: false
组件标签内所绑定的属性,将渲染到根标签上。其他标签想要获得这些属性,也是需要添加 $attrs的
template: `
<label >
<p v-bind="$attrs">{{ label }}</p>//有$attrs
<input
v-bind:value="value"
v-on:input="$emit('input', $event.target.value)"
>//无$attrs
</label>
`
渲染的结果如图
在label上的红色属性是因为允许了继承。
在p标签上的是因为$attrs的添加。
总结加粗
在标签内添加$attrs可以渲染上未注册的属性
inheritAttrs:true 是允许组件绑定的未注册属性渲染到组件根节点上的