>[success] # $attrs 包括 class & style ~~~ 1.于2.x 不同3.x现在 $attrs 包含传递给组件的所有 attribute,包括 class 和 style。 ~~~ >[danger] ##### 在看这个之前 [在看这个之前你需要看这篇文章关于2.x inheritAttrs介绍](https://www.kancloud.cn/cyyspring/vuejs/988817) * 子组件 ~~~html <template> <label> <input type="text" v-bind="$attrs" /> </label> </template> <script> export default { inheritAttrs: false } </script> ~~~ * 父组件 ~~~html <my-component id="my-id" class="my-class"></my-component> ~~~ >[info] ## 2.x 使用 ~~~ 1.当将'inheritAttrs' 为false 时候(默认是true),它只识别在子组件prop绑定的值通过父组件传递, 除了style 和 class 他们无论true 或者flase 只要没有具体定义 他们将都会和子组件最外层的dom的 class 和style 合并 2.如果是默认true,class 和style依旧是之前规则 没有在子组件定义的prop但在父组件使用的属性将替换掉子 组件最外层dom相同属性 3.包含了父作用域中不作为 prop 被识别 (且获取) 的 attribute 绑定 (class 和 style 除外)。当一个组件没有声明 任何 prop 时,这里会包含所有父作用域的绑定 (class 和 style 除外),并且可以通过 v-bind="$attrs" 传入内 部组件,简单理解这句话'我没在子组件定义prop 但是又想让一些属性想prop 一样作用在指定位置我可以使用$attrs' 4.默认true的情况下没有定义的将作用在最外层dom,class和style 是合并,但是现在问题就是我设置了'inheritAttrs' 为false ,那么没定义的一些属性(class 和style除外他们依旧将和最外层dom 一起合并),但是如果这个时候使用 '$attrs' 这些没有被定义的元素在父组件使用时候默认在子组件定义了,那么这些元素可以在我们声明地方使用, class 和style 却被刨除在外 ~~~ >[danger] ##### 举个例子 ~~~ 1.inheritAttrs: false 时候原本向下面案例'id="my-id"' 将不会对最后生成效果有任何体现因为他没有再prop定义 不会增加该熟悉,并且他有不是true 会在自组建最外层dom替换,现在使用了'$attrs' 将id 变成了一个子组件的 一个 prop此时就变成下面效果作用在定义的位置 而不是像true作用在最外层像flase没定义无任何效果 2.但是class 却没有想我们预期一样因为$attrs 不能将class 和style 抽象理解成转换成prop 依旧作用在最外层 dom节点上 ~~~ * 上面例子效果 ~~~html <label class="my-class"> <input type="text" id="my-id" /> </label> ~~~ >[info] ## 3.x ~~~ 1.3.x $attrs 包含所有的 attribute class 和style 不在是自己的一套规则 ~~~ * 上例子在3.x渲染效果 ~~~html <label> <input type="text" id="my-id" class="my-class" /> </label> ~~~