Abdelaziz Mokhnache
Abdelaziz Mokhnache

Reputation: 4349

How to apply Vue.js scoped styles to components loaded via view-router?

How can I apply Vue.js scoped styles to components loaded via <view-router>.

Here is my code:

<template>
  <div id="admin">
    <router-view></router-view>
  </div>
</template>

<style lang="scss" scoped>
#admin {
  .actions {
    display: none;
    span {
      cursor: pointer;
    }
  }
}
</style>

When I visit the /posts a component named Posts will be loaded, inside this component I have a

<div class="actions">
  some content
</div>

The problem is that the style defined in #admin is not applied to .action element. When not scoped, this works fine. The problem come when the #admin component styling is scoped.

Is there any way to do that while keeping the .actions style inside the admin component scoped style tag?

Upvotes: 3

Views: 7435

Answers (3)

rabbitwerks
rabbitwerks

Reputation: 355

The reason why router-view tag wont pass styles to its child is because the router-view itself is not a style-able html tag, therefore you cant apply any styles to it. You can try but it wont render.

Reason: The router-view is essentially a template tag, or placeholder for Vue to anchor to and insert the component or View that gets called for that route. As a result, the router-view tag wont appear in the compiled markup, you will only see the View or Component thats being loaded.

It sort of works the same way as the App Entry point works for the Vue App into the index.html file. At least that's my experience and knowledge.

Also, @Antonio Trapani good answer, I would add that you can even go as far as having a scss file with all your global styles, or styles needed across multiple components, then just @import the styles into the App.vue that will give you access across the whole app. Also, IME.

Hope this helps some. Cheers.

Upvotes: 0

Austin
Austin

Reputation: 108

This is probably what you want https://vue-loader.vuejs.org/en/features/scoped-css.html#deep-selectors

Since your code snippet specifically uses SCSS you'll have to use the /deep/ combinator.


If you want a selector in scoped styles to be "deep", i.e. affecting child components, you can use the >>> combinator:

<style scoped>
.a >>> .b { /* ... */ }
</style>

The above will be compiled into:

.a[data-v-f3f3eg9] .b { /* ... */ }

Some pre-processors, such as SASS, may not be able to parse >>> properly. In those cases you can use the /deep/ combinator instead - it's an alias for >>> and works exactly the same.


So you'd end up with:

<style lang="scss" scoped>
  #admin {
    some-property: some-style;

    /deep/ .actions {
      some-property: some-style;
    }
  }
</style>

Upvotes: 8

Antonio Trapani
Antonio Trapani

Reputation: 811

You can put styles in a separate file and reference it from all components that need it:

<style src="path/to/your/styles" lang="scss" scoped></style>

Upvotes: 3

Related Questions