Vue穿透scoped设置组件样式
为什么用组件样式穿透
有时候希望在组件外修改组件内的样式,由于组件在style标签使用了scoped属性,外部的样式最多影响组件的根标签,没办法对组件内部具体标签进行样式修饰,这时用样式穿透就可实现这些需求。
模板定义
自定义组件my-button
<template>
<view class="root">
<button class="button">按钮</button>
</view>
</template>
测试页面index.vue
<template>
<view class="root">
<my-button class="my-button"></my-button>
</view>
</template>
数据声明:
-
xxx:任意标签元素(元素选择器、类选择器、id选择器等都可以)
-
control-element:xxx内部需要被控制的标签元素(用元素选择器、类选择器、id选择器等都可以)
-
如 xxx 可以是
my-button
或.mybutton
,control-element可以是button
或.button
组件样式穿透方式
一、>>>
style必须用CSS,使用方式如下:
xxx >>> control-element {
/*样式修饰*/
}
如:
<style lang="css">
.my-button >>> .button{
background-color: green;
}
</style>
二、/deep/
Vue2支持,style用SCSS,使用方式如下:
/*嵌套使用*/
xxx {
/deep/ control-element {
/*样式修饰*/
}
}
/*非嵌套使用*/
xxx /deep/ control-element {
/*样式修饰*/
}
如:
<style lang="scss">
/*嵌套使用*/
.my-button {
/deep/ .button {
background-color: red;
}
}
/*非嵌套使用*/
.my-button/deep/ .button {
background-color: red;
}
</style>
三、::v-deep
CSS和SCSS都支持,使用方式如下:
/* 嵌套使用 */
xxx {
::v-deep control-element {
/* 样式控制 */
}
}
/* 非嵌套使用 */
xxx ::v-deep control-element {
/* 样式修饰 */
}
如:
<style lang="scss">
/* 嵌套使用 */
.my-button{
::v-deep .button {
background-color: green;
}
}
/* 非嵌套使用 */
.my-button ::v-deep .button {
background-color: red;
}
</style>
四、:deep()
style必须选择SCSS
① 穿透任意个标签
使用方式如下:
/* 嵌套使用 */
xxx {
:deep() {
control-element1 {
}
control-element2 {
}
...
}
}
/* 非嵌套使用 */
xxx :deep(){
control-element1 {
}
control-element2 {
}
...
}
如:
<style lang="scss" scoped>
/* 嵌套使用 */
.my-button {
:deep() {
.button {
background-color: red;
}
}
}
/* 非嵌套使用 */
.my-button :deep() {
.button {
background-color: red;
}
}
</style>
② 穿透一种标签
使用方式如下:
/* 嵌套使用 */
xxx{
:deep(control-element) {
/* 样式修饰 */
}
}
/* 非嵌套使用 */
xxx :deep(control-element) {
/* 样式修饰 */
}
如:
<style lang="scss" scoped>
/* 嵌套使用 */
.my-button{
:deep(.button) {
background-color: green;
}
}
/* 非嵌套使用 */
.my-button :deep(.button) {
background-color: red;
}
</style>
原文地址:https://blog.csdn.net/weixin_74261199/article/details/142595048
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!