Vue的生态进展中的 style 动态变量注入知识
在 Vue RFC 中有一个关于样式的提案 SFC style CSS variable injection,这个 RFC 为 Vue 开发者提供了一种使用组件的响应性数据作为 CSS 变量的方法。
在 Vue 3 中,只需一个简单的语法,我们就可以在运行时更新样式。
在本文中,我们将了解如何使用这些 SFC 样式,它是如何工作的,然后了解一些来自 RFC 的高级知识。
Single File Component : 单文件组件,简称 SFC
如何使用 SFC 样式?
要使用这个特性,只需要两个步骤:
- 在组件的
script
中声明一个响应式变量。 - 在 css 中使用
v-bind
来使用这个变量。
举个粟子:
<template> <div> <div class="text">hello</div> </div> </template> <script> export default { data() { return { color: 'red', } } } </script> <style> .text { color: v-bind(color); } </style>
如此 so easy。
如果查看浏览器中的组件,可以看到元素从数据中正确地获得了其颜色的值:
这也适用于更复杂的数据结构,假设我们有一个名为fontStyles
的对象,该对象中有一个weight
的属性。
我们仍然使用v-bind
访问它,但因为我们传递是一个对象,所以需要使用 JS 表达式来访问这个内部属性,且需要将表达式括放在引号中。
<template> <div> <div class="text">hello</div> </div> </template> <script> export default { data() { return { color: 'red', font: { weight: '800' } } } } </script> <style> .text { color: v-bind(color); /* wrapped in quotes */ font-weight: v-bind('font.weight'); } </style>
Vue 中的响应式样式
无论我们是使用 JS 表达式还是仅仅使用根级数据绑定,我们都可以利用 Vue 的内置响应式在运行时更新样式。
假设我们希望能够使用一个按钮来更改文本的颜色,那么可以这样做。
<div> <div class="text">hello</div> <button @click="color = 'blue'"> Make Blue </button> </div>
我们所要做的就是改变对应的变量值,CSS 样式就会自己更新。这就是这个特性如此强大的原因,它为我们提供了一种干净的方式来修改页面在运行时的外观。
Vue SFC 样式变量如何工作
了解了使用方式之后,我们来看下 Vue 是怎么做到的。如果我们检查元素,我们可以更好地了解 Vue 如何运作它的魔力。
在我们的样式节中引用的任何变量都被作为内联样式添加到组件的根元素中。
像普通的 CSS 那样写,我们声明 CSS 变量-015c408c-color
,并将其设置为red
,将变量--015c408c-font_weight
,设置为800
。
element.style { /* root element */ --015c408c-color: red; --015c408c-font_weight: 800; } .text { color: var(--015c408c-color); font-weight: var(--015c408c-font_weight); }
然后就是将 v-bind
转换成使用 CSS 变量方式。
然后,每当响应性数据发生变化时
- 我们的内联样式改变了,这意味着…
- 我们的 CSS 变量改变了,这意味着…
- 最终样式更改为响应式的新值
这就是如何在运行时更新样式就像上面的 color
做的那样。
CSS 变量在子组件中不可用
为了避免继承问题,定义的 CSS 变量对它的任何子组件都不可用。
例如,如果我们向现有组件添加一个子组件。
<template> <div> <div class="text">hello</div> <button @click="color = 'blue'"> Make Blue </button> <child-component /> </div> </template> <script> import ChildComponent from './ChildComponent.vue' export default { components: { ChildComponent }, data() { return { color: 'red', font: { weight: '800' } } } } </script> <style> .text { color: v-bind(color); /* expressions (wrap in quotes) */ font-weight: v-bind('font.weight'); } </style>
假设子组件是这样构建的。
<template> <div class="child-text"> Child Component </div> </template> <style> .child-text { color: v-bind(color); } </style>
这不会改变颜色,因为我们的子组件不知道任何 CSS 变量。
检查浏览器支持情况
如果你想要项目使用该特性,需要先检查一下浏览器对 CSS 变量的支持情况
总结
这是一个非常有趣的特性,类似于我们上次讲的 script setup 语法,它最终将走出实验阶段,合并到 Vue 3 中。
将 Vue 用于 CSS 变量和 SFC 样式变量是向 Vue 组件添加响应式样式的直观方式。
码云笔记 » Vue的生态进展中的 style 动态变量注入知识