组件中的非作用域样式仅在切换路由时应用一次

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

Vue.js documentation for Scoped CSS 提到

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

我构建了 example application for vue-router 并使用了两个单个文件组件而不是示例的字符串模板 - 呈现符合预期。

然后我尝试在组件中应用范围样式和非范围样式。第一个我有

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

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

和第二个

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

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

思路是选择特定路线时全身背景切换

scoped 样式没问题 - 它们会根据路线变化。

非作用域的没有(截图来自 Chrome Dev Tools):

换句话说,看起来样式是堆叠的,之前覆盖的属性没有更新这是预期的行为吗?

我为此打开了一个 bug report,它最终是预期的行为。报告评论摘要:

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.

我对问题的总结:

  • 最初(没有路由,没有渲染组件)没有注入任何东西
  • 第一个组件在路由开关上渲染,它的style被注入
  • 第二个组件在路由开关上渲染,它的style被注入并覆盖了之前的style
  • 进一步的路由切换不会注入任何东西,因为每个组件都已经渲染过一次。因此,最后使用的 style 仍然是权威的。

因此,我将回退到将 body class 绑定到当前组件的 data