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

大城市里の小女人 提交于 2019-12-10 23:08:11

问题


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?


回答1:


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>



回答2:


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>



回答3:


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.



来源:https://stackoverflow.com/questions/46140062/how-to-apply-vue-js-scoped-styles-to-components-loaded-via-view-router

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