组件中的非作用域样式仅在切换路由时应用一次
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):
- 在初始应用程序加载(尚未路由)时,背景为白色(这没关系 - 这是默认设置,
/
没有路由)。
- 选择路线时,正文样式会正确应用(例如,第一个组件的
green
)
- 当切换路由并加载第二个组件时,背景会更改为新颜色,从 Chrome 开发工具看来,
background-color
的当前样式已被覆盖。所有其他组件元素均已正确呈现(内容和作用域样式)
- 更多的开关保持相同的背景(并且相关组件的其他元素再次正确呈现)。 Chrome Dev Tools 没有变化(上面最后一个视图没有变化)
换句话说,看起来样式是堆叠的,之前覆盖的属性没有更新这是预期的行为吗?
我为此打开了一个 bug report,它最终是预期的行为。报告评论摘要:
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
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):
- 在初始应用程序加载(尚未路由)时,背景为白色(这没关系 - 这是默认设置,
/
没有路由)。 - 选择路线时,正文样式会正确应用(例如,第一个组件的
green
)
- 当切换路由并加载第二个组件时,背景会更改为新颜色,从 Chrome 开发工具看来,
background-color
的当前样式已被覆盖。所有其他组件元素均已正确呈现(内容和作用域样式)
- 更多的开关保持相同的背景(并且相关组件的其他元素再次正确呈现)。 Chrome Dev Tools 没有变化(上面最后一个视图没有变化)
换句话说,看起来样式是堆叠的,之前覆盖的属性没有更新这是预期的行为吗?
我为此打开了一个 bug report,它最终是预期的行为。报告评论摘要:
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