In depth explanation of style features in vue3 single file component

  • 2021-11-13 06:39:47
  • OfStack

Directory style scoped
style module
State-driven dynamic css
Summarize

style scoped

Attention should be paid to:

Styles do not affect other components, but only take effect on the current component. The root element of a child component is affected by both the scope style of the parent component and the scope style of the child component. The purpose of this is to allow the parent component to adjust the layout of the child component. There are three special selectors:

1. Depth selector: Can affect child components. Use pseudo class = > : deep (cls: Selector of Influence)


    .a :deep(.b) {
        ...
    }

2. Slot selector: Can affect the style of slot content. Use pseudo-class = > : slotted (selector)


    :slloted(.a) {
        ...
    }

3. Global selector: It is the style that affects the global. Use pseudo-class = > : global (selector)


    :slloted(.a) {
        ...
    }

scoped style can coexist with style

style module

module is included in the style tag. Its style and style scoped1 style can only be scoped on the current component.

This compiles css to css modules and exposes the component $styles object to use the css style


<template>
  <p :class="$style.red">
    This should be red
  </p>
</template>

<style module>
.red {
  color: red;
}
</style>

You can assign a value to module to customize the exposed object name


<template>
  <p :class="style.red">
    This should be red
  </p>
</template>

<style module='style'>
.red {
  color: red;
}
</style>

You can use useCssModule () api to use cssModule in a combined api.


//  Default ,  Return  <style module>  Classes in 
useCssModule()

//  Naming ,  Return  <style module="classes">  Classes in 
useCssModule('classes')

State-driven dynamic css

You can use v-bind () to correlate css values to dynamic component states


<template>
  <div class="text">hello</div>
</template>

<script>
export default {
  data() {
    return {
      color: 'red'
    }
  }
}
</script>

<style>
.text {
  color: v-bind(color);
}
</style>

Summarize


Related articles: