Masoud Shayan
Masoud Shayan

Reputation: 83

How to style a nested component from its parent component in Vuejs?

I am going to create a layout like 'header sidebar main-content sidebar footer ' with flexbox by Vuejs. I created separate .vue files for each part of the layout , I mean something like a sidebar.vue and a header.vue and so on ....
And I am going use them in App.vue file like :

<template>
  <div id="app">
    <app-header ></app-header>
    <app-sidebar></app-sidebar>
    <app-content></app-content>
    <app-sidebar></app-sidebar>
    <app-footer></app-footer>
  </div>
</template>

<script>
import header from "./components/header";
import sidebar from "./components/sidebar";
import content from "./components/content";
import footer from "./components/footer";

export default {
  components: {
    "app-header": header,
    "app-sidebar": sidebar,
    "app-content": content,
    "app-footer": footer
  }
};
</script>

<style lang="scss">

body {
  margin: 0;
  padding: 0;
}


#app {
  border: 3px solid red;
  min-height: 100vh;

  display: flex;
  flex-wrap: wrap;

  > * {
    border: 1px solid black;
  }
}

the main problem is I can not select these custom nested components from App.vue file to style them. for example i can not use app-header{} like other normal tags in html and css to select it and style it within style tags inside of App.vue file . is there anyway to solve it ?
NOTE : I know I can assign a class to each of these nested components and then select them to use with css class selector .

Upvotes: 2

Views: 3786

Answers (1)

Scornwell
Scornwell

Reputation: 605

I would handle this by creating a property in each of the child components (maybe HeaderClass, BodyClass, and so on). That way, any component that consumes these child components can pass whatever classes they desire and style them accordingly.

<app-header :headerclass="parent-header-class"> </app-header>

Inside of your child component, you can use these properties and v-bind the class inside the HTML, as shown in the example below:

<template>
    <div :class=`${headerClass} internal-class-example button`> </div>
</template>

Note: This does not allow you to use any scoped parent CSS to pass to the child. The classes you pass down must be global. Otherwise, the child component will not know what it is.

Upvotes: 2

Related Questions