티스토리 뷰
deep selector란?
부모 컴포넌트에서 자식 컴포넌트에 영향을 미치게 하려면, >>> (deep selector) 를 사용할 수 있다
deep selector 적용하는 방법 3가지
<style scoped>
.a >>> .b { /* ... */ }
</style>
<style scoped>
.a /deep/ .b { /* ... */ }
</style>
<style scoped>
.a::v-deep .b { /* ... */ }
</style>
글쓴이는 회사에서는 vue2를 사용하고 있으므로 ::v-deep . child-class로 사용합니다.
vue3를 사용하고 있다면 ::v-deep(.child-class)로 사용합니다
1. 각 컴포넌트별 클래스 스타일 추가
부모(Parent) 컴포넌트
<template>
<div class="parent">
<div class="title">Parent 컴포넌트입니다</div>
<child></child>
</div>
</template>
<script lang="ts">
import { defineComponent } from "vue"
import Child from "../components/Child.vue"
export default defineComponent({
components: {
Child
},
name: "Parent"
})
</script>
<style scoped>
.parent > div:first-child {
color: red;
}
</style>
자식(Child) 컴포넌트
<template>
<div class="child">
<div>Child 컴포넌트입니다</div>
</div>
</template>
<script lang="ts">
import { defineComponent } from "vue"
export default defineComponent({
name: "Child"
})
</script>
<style scoped>
.child > div:first-child {
color: blue;
}
</style>
2. 부모 컴포넌트에서 자식 컴포넌트 클래스 스타일 추가
scoped 속성 때문에 현재 컴포넌트 내에서만 스타일 적용이 가능하다
부모(Parent) 컴포넌트
<template>
<div class="parent">
<div class="title">Parent 컴포넌트입니다</div>
<child></child>
</div>
</template>
<script lang="ts">
import { defineComponent } from "vue"
import Child from "../components/Child.vue"
export default defineComponent({
components: {
Child
},
name: "Parent"
})
</script>
<style scoped>
.parent > div:first-child {
color: red;
}
.child > div:first-child {
color: blue;
}
</style>
자식(Child) 컴포넌트
<template>
<div class="child">
<div>Child 컴포넌트입니다</div>
</div>
</template>
<script lang="ts">
import { defineComponent } from "vue"
export default defineComponent({
name: "Child"
})
</script>
<!--<style scoped>-->
<!--.child > div:first-child {-->
<!-- color: blue;-->
<!--}-->
<!--</style>-->
위와 같이 Child 컴포넌트에는 스타일이 적용되지 않는 결과를 볼 수 있다
3. 부모 컴포넌트에서 자식 컴포넌트 클래스 스타일 추가(v-deep으로 해결)
부모 컴포넌트
<template>
<div class="parent">
<div>Parent 컴포넌트입니다</div>
<child></child>
</div>
</template>
<script lang="ts">
import { defineComponent } from "vue"
import Child from "../components/Child.vue"
export default defineComponent({
components: {
Child
},
name: "Parent"
})
</script>
<style scoped>
.parent > div:first-child {
color: red;
}
.parent::v-deep .child > div:first-child {
color: blue;
}
</style>
자식(Child) 컴포넌트: 2번과 동일
참고문서: https://vue-loader.vuejs.org/guide/scoped-css.html#deep-selectors
data-v-* 란?
Scoped CSS를 사용하는 경우에 data-v-* 가 붙는 경우를 확인할 수 있습니다.
'vue js' 카테고리의 다른 글
Conflict between mouseup and click event (0) | 2023.02.27 |
---|---|
vue js reset component data (0) | 2019.07.24 |
댓글