Vue3 使用 :deep() 穿透修改 teleport 组件样式
在 Vue3 中,使用 ':deep()' 可以穿透子组件的样式,但是对于 teleport 组件,由于其在 DOM 结构中并不是直接嵌套在父组件中的,而是通过 Portal 挂载到 body 中,因此无法通过 ':deep()' 来修改其样式。
如果要修改 teleport 组件的样式,可以使用以下方法:
- 在 teleport 组件的 props 中添加一个 class 属性,允许父组件传递一个自定义的 class 名。
- 在父组件中定义一个 class,使用 '::v-deep' 修饰器来穿透 teleport 组件的样式。
- 将 class 属性传递给 teleport 组件,使其应用到组件的根元素上。
例如:
<!-- 父组件 -->
<template>
<div class='parent'>
<teleport to='body' :class='teleportClass'>
<div class='child'>Hello World</div>
</teleport>
</div>
</template>
<script>
export default {
data() {
return {
teleportClass: 'my-teleport-class',
}
},
}
</script>
<style scoped>
.parent ::v-deep .my-teleport-class .child {
color: red;
}
</style>
这样就可以通过父组件的 teleportClass 属性来修改 teleport 组件中的样式了。注意,这里使用了 '::v-deep' 修饰器来穿透 teleport 组件的样式,而不是使用 ':deep()'。
原文地址: https://www.cveoy.top/t/topic/mA0Y 著作权归作者所有。请勿转载和采集!