说明

scoped 中的元素选择器

元素选择器应该避免在 scoped 中出现。

scoped 样式中,类选择器比元素选择器更好,因为大量使用元素选择器是很慢的。

为了给样式设置作用域,Vue 会为元素添加一个独一无二的 attribute,例如 data-v-f3f3eg9。然后修改选择器,使得在匹配选择器的元素中,只有带这个 attribute 才会真正生效 (比如 button[data-v-f3f3eg9])。

问题在于大量的元素和 attribute 组合的选择器 (比如 button[data-v-f3f3eg9]) 会比类和 attribute 组合的选择器慢,所以应该尽可能选用类选择器。

反例

<template>
  <button>X</button>
</template>

<style scoped>
button {
  background-color: red;
}
</style>

正例

<template>
  <button class="btn btn-close">X</button>
</template>

<style scoped>
.btn-close {
  background-color: red;
}
</style>
文档更新时间: 2021-05-13 10:36   作者:姚连洲