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

守給你的承諾、 提交于 2019-12-11 17:58:24

问题


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 .


回答1:


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.



来源:https://stackoverflow.com/questions/57908690/how-to-style-a-nested-component-from-its-parent-component-in-vuejs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!