scoped的原理:
1、为组件实例生成一个唯一标识,给组件中的每个标签对应的dom元素添加一个标签属性:data-v-xxxx
2、给<style scoped>中的每个选择器的最后一个选择器添加一个属性选择器,原选择器[data-v-xxxx],如:原选择器
为.container #id div,则更改后选择器为.container #id div[data-v-xxxx]
转译前的vue代码
<template>
<div class="example">hello world</div>
</template>
<style scoped>
.example {
color: red;
}
</style>
转译后:
<template>
<div class="example" data-v-49729759>hello world</div>
</template>
<style scoped>
.example[data-v-49729759] {
color: red;
}
</style>
作用:实现组件的私有化,不对全局造成样式污染,表示当前style属性只属于当前模块。
注意:实际开发中,建议在每个组件的 style 身上都加上 scoped 属性。