WoJ
WoJ

Reputation: 29987

Non-scoped styling in components applied only once when switching routes

Vue.js documentation for Scoped CSS mentions that

You can include both scoped and non-scoped styles in the same component

I built the example application for vue-router and used two single file components instead of the string templates of the example - the rendering is as expected.

I then tried to apply both scoped and non-scoped styles in the components. In the first one I have

<style scoped>
div {
    color: white;
    background-color: blue;
}
</style>

<style>
body {
    background-color: green;
}
</style>

and the second one

<style scoped>
div {
    color: white;
    background-color: red;
}
</style>

<style>
body {
    background-color: yellow;
}
</style>

The idea is to have the whole body background switch when choosing a specific route.

The scoped styles are OK - they change depending on the route.

The non-scoped ones do not (screenshots are from Chrome Dev Tools):

enter image description here

enter image description here

In other words, it looks like the style is stacked and previously overwritten properties are not updated Is this expected behaviour?

Upvotes: 3

Views: 2033

Answers (1)

WoJ
WoJ

Reputation: 29987

I opened a bug report for this and it ended up being expected behaviour. The summary from the report comments:

Thorsten Lünborg:

Yes, this is expected. Vue (or rather, webpack) does not insert and remove these styles, as you seem to think. They are injected into the head once the component renders, and never removed.

A common pattern is to extarct all CSS into a single .css file in production, which would have the same result.

My summary in the context of the question:

  • initially (no route, no component rendered) nothing was injected
  • the first component is rendered on route switch, its style is injected
  • the second component is rendered on route switch, its style is injected and overwrites the previous style
  • further route switches do not inject anything as each component was already rendered once. The last style used therefore stays as the authoritative one.

I will therefore fallback on binding the body class to the current component's data

Upvotes: 2

Related Questions