vue3样式穿透用法
在Vue3中,样式穿透可通过以下方式实现:
1. 基础用法
使用::v-deep
伪类实现样式穿透(兼容Vue2语法):
.parent ::v-deep .child-component {color: red;
}
2. 推荐方式
使用:deep()
伪函数(Vue3推荐写法):
.parent :deep(.child-component-inner) {padding: 10px;
}
3. 插槽内容样式
使用:slotted()
处理插槽内容:
:slotted(.slot-content) {background: #f0f0f0;
}
4. 全局样式
在scoped样式中定义全局规则:
:global(.global-class) {font-size: 16px;
}
5. 动态选择器
结合属性选择器使用:
:deep([data-test="item"]) {border: 1px solid blue;
}
使用场景示例
<template><el-dialog><div class="custom-content">需要定制的弹窗内容</div></el-dialog>
</template><style scoped>
/* 修改Element Plus弹窗标题 */
:deep(.el-dialog__header) {background: #409eff;
}/* 定制插槽内容样式 */
:slotted(.custom-content) {font-weight: bold;
}
</style>
注意事项
- 优先考虑组件props/custom class设计
- 避免过度使用样式穿透
- 注意样式优先级问题
- 使用scoped限定作用域
- 在Vue3中已废弃
/deep/
和>>>
语法
推荐结合CSS变量使用更灵活的样式定制方案:
:deep(.child-component) {--theme-color: #42b983;color: var(--theme-color);
}