vuejs 教程,vue3.0 文档,vuejs 实战,前端框架,vuejs 入门,vue3.0 迁移,vue3资讯,Vue3最新动态,vuejs 中文社区,javascript中文网,vuejs 面试题,vuejs bug

# $attrs includes class & style
非兼容

# Overview

$attrs now contains all attributes passed to a component, including class and style.

# 2.x Behavior

class and style attributes get some special handling in the Vue 2 virtual DOM implementation. For that reason, they are not included in $attrs, while all other attributes are.

A side effect of this manifests when using inheritAttrs: false:

  • Attributes in $attrs are no longer automatically added to the root element, leaving it to the developer to decide where to add them.
  • But class and style, not being part of $attrs, will still be applied to the component's root element:
<template>
  <label>
    <input type="text" v-bind="$attrs" />
  </label>
</template>
<script>
export default {
  inheritAttrs: false
}
</script>
1
2
3
4
5
6
7
8
9
10

when used like this:

<my-component id="my-id" class="my-class"></my-component>
1

...will generate this HTML:

<label class="my-class">
  <input type="text" id="my-id" />
</label>
1
2
3

# 3.x Behavior

$attrs contains all attributes, which makes it easier to apply all of them to a different element. The example from above now generates the following HTML:

<label>
  <input type="text" id="my-id" class="my-class" />
</label>
1
2
3

# Migration Strategy

In components that use inheritAttrs: false, make sure that styling still works as intended. If you previously relied on the special behavior of class and style, some visuals might be broken as these attributes might now be applied to another element.

# See also

Js中文网,专注分享前端最新技术、大厂面试题、聊点程序员轶事、职场感悟,做前端技术的传播者.

加入前端布道师交流群

扫描二维码回复 加群 学习,与大厂大佬讨论技术.