Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

:Host CSS equivalent for VueJS Templates?

Tags:

css

vue.js

I tried out Angular before switching to Vue and found the :host selector in their components to be very handy. The jist of this is that it applies the stylings for :host to the component itself.

Is there an equivalent of this that works with .vue files in they <style scoped></style> section?

Examples:

Using Scoped

Parent:

<template>
  <div class="host">
      <layout-header :open-nav="openNav" @toggle-open="toggleOpen"></layout-header>
      <layout-sidebar :open-nav="openNav"></layout-sidebar>
      <layout-content></layout-content>
      <layout-footer></layout-footer>   
  </div>
</template>
<style scoped>
  .host {
    display: flex;
    height: 100%;
    width: 100%;
    flex-direction: column;
  }
</style>

Content:

(<layout-content>)

  <div class="host">
    stuff
  </div>
<style scoped>
  .host{
    flex: 1;
  }
</style>

Output:

(removing the header, footer, and sidebar for simplicities sake.)

This results in the header, sidebar, content, and footer inheriting the parents css if they have a .host class.

HTML:

<div data-v-238e7577="" class="host">
  <div data-v-7412829c="" data-v-238e7577="" class="host">stuff</div>
</div>

The CSS applied to the child element:

enter image description here

like image 909
Douglas Gaskell Avatar asked Jan 28 '19 00:01

Douglas Gaskell


1 Answers

There is no equivalent for Angular's :host in Vue.

The closest you are gonna get is by using CSS module.

Demo: App.vue in https://codesandbox.io/s/o4orw9nz35

<template>
  <div id="app" :class="$style.container">
    <p class="red">p tag</p>
    <div class="blue">div tag</div>
  </div>
</template>

<style lang="scss" module>
.container :global {
  .red {
    color: red;
  }
  .blue {
    color: blue;
  }
}
</style>

Note how the .container class is used as $style.container as class in the root div.

CSS module will generate unique class name for .container, making it impossible to have class name collisions.


What does :global do?

CSS module transform the CSS class name into something unique by default.

for e.g. .container will be transformed into something like .container_7ba5bd90 when used as $style.container.

To avoid this transformation on certain classes, use :global to wrap them.

(Explanation for :global can be found here.)

like image 109
Jacob Goh Avatar answered Sep 22 '22 12:09

Jacob Goh