组件样式作用域
Vue 提供 scoped 属性实现组件样式隔离。
基本用法
vue
<style scoped>
.title {
color: red;
}
</style>
编译后:
CSS
.title[data-v-f3f3eg9] {
color: red;
}
混合使用
vue
<style>
/* 全局样式 */
.global {
font-size: 16px;
}
</style>
<style scoped>
/* 局部样式 */
.local {
color: blue;
}
</style>
子组件样式穿透
vue
<style scoped>
/* 深度选择器 */
:deep(.child-class) {
color: red;
}
/* 旧版写法 */
::v-deep(.child-class) {
color: red;
}
</style>
动态组件样式
vue
<style scoped>
.is-active {
background: blue;
}
</style>
<template>
<div :class="{ 'is-active': isActive }">内容</div>
</template>
使用
scoped时,子组件的根元素会同时受父组件和子组件样式影响。
要点总结
scoped属性为样式添加数据属性隔离- 可混合使用全局和局部样式
- 使用
:deep()穿透子组件样式 - 推荐默认使用
scoped避免样式污染
📝 发现内容有误?点击此处直接编辑