Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Why did Vue3 choose the CSS variable

2025-03-30 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

Editor to share with you why Vue3 chose CSS variable, I believe most people do not know much about it, so share this article for your reference, I hope you can learn a lot after reading this article, let's go to know it!

Vue 3 adds an experimental feature-"state-driven CSS variables for single file components"

Seeing this, I have the following questions on my mind?

What is the CSS variable?

There is a definition of a variable in Sass/Less, so why do you need to use a CSS variable?

The existing Vue is not defined to dynamically bind CSS in the way of: style, so what's the difference between CSS variables and this approach?

What did Vue 3 do to make SFC (single file component) better use CSS variables?

These issues are discussed below.

CSS variable basis

The CSS variable is not a product of a framework, but a standard specification defined by the CSS author.

The CSS variable, also known as the CSS custom property, contains values that can be reused throughout the document. The value is set by the custom attribute tag (for example:-- main-color: black;), and the value is obtained by the var () function (for example: color: var (--main-color);)

Why choose two hyphenation lines (- -) to express? Because of variables? Used by Sass, @ used by Less. In order not to conflict, the official CSS variable is changed to two hyphens.

A simple example of CSS variable is as follows. The basic demo address of CSS variable

The scope of the I am Parent I am Child .parent {/ * variable is the valid scope of the selector in which it is located, so the .parent cannot read the variable in child * / color: var (--body-child); / * define the variable * /-- parent-color: blue;} .child {/ * read the variable through var * / color: var (--parent-color) -- child-color: green;}

Result display

We now define variables in .parent-- parent-color: blue;, uses color: var (--parent-color) in .child.

It should be noted that the scope of a variable is the valid scope of the selector in which it is located, such as the one defined in .child-- child-color: green;, cannot be read in .parent and is valid only for elements under the .child element.

If you want to be able to access it all in the HTML document, you can define it in the class: root

In addition to the basic use, there are the following points to pay attention to

The naming of CSS variables is case-sensitive, that is,-- myColor and-- mycolor are different.

The var () parameter can use the second parameter to set the default value, which will be used when the variable is invalid

The CSS variable provides a way for JavaScript to communicate with CSS. In JS, we can manipulate CSS, just as we can manipulate the normal CSS attribute.

/ / get the CSS variable element.style.getPropertyValue ("--my-var") on a Dom node; / / get the CSS variable getComputedStyle (element) .getPropertyValue ("--my-var") on any Dom node; / / modify the CSS variable element.style.setProperty ("--my-var", jsVar + 4) on a Dom node

Here is a demonstration of the simplest use, which can be seen in the MDN documentation

Using CSS variables in Vue 2

As mentioned above, the CSS variable is not a product of a framework, but a standard specification for native CSS. Then it is certainly possible to use CSS variables directly in Vue 2, and there are no restrictions.

The key is how to synchronize the state in the Vue component into the CSS variable, which is actually very simple, just through Style binding. Vue 2 demo address

I am Child 1 I am Child 2 Change Red TO Blue export default {name: "HelloWorld", props: {msg: String,}, data () {return {styleVar: {"- colorBlue": "blue", "--colorRed": "red", "--fontSize": "30px" "--fontSizeTest": "30px",},} }, methods: {onClick () {this.styleVar ["--fontSizeTest"] = "40px";},},}; .child-1 {color: var (--colorBlue); font-size: var (--fontSize);} .child-2 {color: var (--colorRed); font-size: var (--fontSizeTest);}

Results:

We only need to set: style= "styleVar" in the root element of the component (if you want the component to be available, it must be placed under the root element), we can bind the state and the CSS value of the component in Vue 2.x, and the binding relationship is responsive. For example, I define a method to change the value of font-size, which can be updated in real time.

OnClick () {this.styleVar ["- fontSizeTest"] = "40px";}

Demonstration of the effect:

: style VS CSS variable

There is a problem here, the existing Vue can be defined by: style to dynamically bind CSS, for example, I can directly do the following binding in the above .child-1, the effect is the same as above.

I am Child 1

Then why should I use the CSS variable? Does it really make sense to go to such a lot of trouble?

I have summed up the following two reasons:

Reason 1:

Complex websites have a lot of CSS code and usually a lot of duplicate values. When a state in a component is used in dozens of places, you may need to bind many: style. On the one hand, the code will not appear to be readable, and on the other hand, the performance should be worse than the native one. After all, you have to bind the change to the Vue instruction to each element (this has not been verified yet).

Through the CSS variable, you can directly use it inside the component by setting the variable in the root element of the component

Reason 2: the use of pseudo elements

If we use: style directly, we cannot style pseudo elements, but the CSS variable can

P::first-line {color: var (--theme-secondary-color);}

Using CSS variables in Vue 3

Although CSS variables can be used in Vue 2.x, they need to be passed in through style binding, which seems less elegant, so some optimizations have been made in Vue 3

New vars binding

Hello export default {data () {return {color: "red",};},}; .text {color: var (--color);}

In SFC in Vue 3, the style tag supports vars binding, which accepts object key-value pairs to inject CSS variables, as shown above. For the results, please see the Vue 3 demo address.

These variables are directly bound to the root element of the component, and in the above example, the final rendering is as follows:

Hello

Use with

When vars is used with, the applied CSS variable will be prefixed with the component's Scoped id, and the Scoped id will be automatically added when accessed.

For example, we write as follows:

H2 {color: var (--color);}

After compilation, it becomes

H2 {color: var (--6b53742-color);}

What if we want to access the global CSS variable in this case? That is, we don't want to add Scoped Id, so write something like this:

H2 {color: var (--color); font-size: var (--global:fontSize);}

This compiles to the following result:

H2 {color: var (--6b53742-color); font-size: var (--fontSize);}

Variables in Less/Sass VS CSS variables

The most important thing I understand is that CSS variables can communicate better with JavaScript, acting as a bridge between CSS and JavaScript. This is quite obvious in Vue.

In addition, let's take a look at an example of switching themes. If we use the Sass variable, it looks like this:

$color-primary: blue; $color-text: black; $color-bg: white; / * invert * / $color-primary-invert: red; $color-text-invert: white; $color-bg-invert: black; .component {color: $color-text; background-color: $color-bg; a {color: $color-primary;} .component-dark {color: $color-text-invert; background-color: $color-bg-invert A {color: $color-primary-invert;}}

We have two themes, one is general theme and the other is dark mode (dark). Note that in dark mode, we need a new color variable to update the old color variable. If there are a lot of such settings, we will be very distressed.

If you look at the CSS variable setting,

: root, [data-theme= "default"] {--color-primary: blue; / * color contrasts * /-- color-bg: white;-- color-contrast-lower: hsl (0,0%, 95%);-- color-contrast-low: hsl (240,1%, 83%);-- color-contrast-medium: hsl (240,1%, 48%);-- color-contrast-high: hsl (2404%, 20%) -- color-contrast-higher: black;} [data-theme] {background-color: var (--color-bg); color: var (--color-contrast-high);} [data-theme= "dark"] {--color-primary: red; / * color contrasts * /-- color-bg: black;-- color-contrast-lower: hsl (240,6%, 15%) -- color-contrast-low: hsl (252.4%, 25%);-- color-contrast-medium: hsl (240,1%, 57%);-- color-contrast-high: hsl (0,0%, 89%);-- color-contrast-higher: white;}

In this case, we don't need to define an additional color variable, because we just need to set the CSS variable to the correct value.

The reason why the above usage is different, I understand that the SASS variable is compile time, that is, the preprocessor has parsed before it is output to the browser, while the browser parses the CSS variable at run time.

In addition, the preprocessor and CSS variables do not conflict, and their combination can better improve our open experience.

Disadvantages-browser compatibility issues

At present, the support of CSS variable is not very good. IE does not support all of them at present, but as mentioned above, we are still optimistic about its future.

To deal with its compatibility, we can also write as follows:

A {color: # 7F583F; color: var (--primary);} above is all the content of the article "Why Vue3 chooses CSS variable". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report