How to use CSS custom variables in Vue

How to use CSS custom variables in Vue

The CSS custom variable function has been around for a long time, but it is not widely used in actual development. The reason is that preprocessors such as less and sass already have the function of defining variables, and Vue and react are very convenient for setting style. People may think that using css to define variables is inconvenient and unnecessary. In fact, it is not the case. Let's take the most intuitive example: "How to use Vue to set the style of pseudo-class pseudo-elements". This is a century-old problem. Most people may solve it by changing the class name, but what should I do if there are many styles to be modified, or I want to render different styles with different data? Today I will address this issue directly. First let's understand what CSS custom variables are. Simple use:

<style>
div {
    --bg-color : pink; //define variable color : var( --bg-color ) //use variable through var function}
</style>
<div>hello</div>

You will get a pink hello. Variables defined in the parent are also available to the child elements and their pseudo-classes.

<style>
div {
    --bg-color : pink; //define the variable color : var( --bg-color ); //use the variable through the var function}
div:hover {
    background-color : var( --bg-color );
}
div span {
    background-color : var( --bg-color );
}
</style>
<div>hello <span>world</span> </div>

The var function can also set a default value. You can also set a default value when the custom variable cannot be found.

<style>
div {
    color : var( --bg-color, pink ); // The second parameter is the default value background-color : var( --bg-color ,--color,--a,red ); // You can even set multiple variables, it will look for them from left to right }
</style>
<div>hello</div>

This concludes the introduction to CSS custom variables. Next, let's look at its use in Vue. You can set the value of the variable in the style attribute of the tag.

<template>
	<div class="box" @click="changeColor" :style="{'--a' : a}">hello</div>
</template>
export default {
  data(){
    return {
      a : 'blue',
    }
  },
  methods: {
    changeColor(){
      this.a = this.a === 'blue' ? "red" : "blue"
    }
  }
}
</script>
<style>
  .box {
      color : var(--a);
  }
  .box:hover {
    background-color : var(--a);
  }
</style>

Clicking on a div will change its font color and background color when it is hovered. At this point you will find that by customizing CSS variables, you can easily modify its style and directly modify the properties of its pseudo-classes. Since child elements can share the parent's custom variables, you can use the parent's own variables directly in the child component.

// Parent component <template>
	<div class="box" :style="{'--a' : a}">hello <Child></Child></div>
</template>
export default {
  components : {
      Child
  },
  data(){
    return {
      a : 'blue',
    }
  }
}
</script>

//Child component
<template>
  <span>world</span>
</template>

<style lang="less">
  span {
      color : var(--color);
  }
</style>

The effect is amazing if you try it out. In this way, we can modify the state of the parent component to change the style of the child component, bypassing the value transfer between the child and parent components. Note: The subcomponent must be mounted in the scope class where the variable can be used.

From the above example, we can see the convenience of sub-definition variables. For ease of use, you can set variables through vue custom instructions.

   // vue3 custom directive.
      function change(el,binding){
        for(let [key,value] of Object.entries(binding.value)){
            el.style.setProperty('--'+key, value);
        }
    }
  app.directive(css, {
        mounted(el,binding){
            change(el,binding)
        }
        updated(el, binding) {
            change(el,binding)
        }
       
    })

Note that modifying CSS variables using el.style['--color'] = 'red' is invalid and must be set using the style.setProperty api. After registering the instruction we can.

<template>
	<div v-css="{a,b}" class="box" @click="changeColor"></div>
</template>
export default {
  data(){
    return {
      a : 'blue',
      b : 'pink'
    }
  },
  methods: {
    changeColor(){
      this.a = this.a === 'blue' ? "red" : "blue"
      this.b = this.b === 'pink' ? "yellow" : "pink"
    }
  }
}
</script>
<style>
  .box {
    width : 100px;
    height : 100px;
    background-color : var(--a);
  }
  .box:hover {
    background-color : var(--b);
  }
</style>

It greatly facilitates Vue's operation on style.

Based on this, I made some optimizations and extensions, and opened up a tool, which has been published on npm. Address www.npmjs.com/package/vue… . Welcome everyone to download and experience it. If you like it, you can also star it.

The above is the details of how Vue uses CSS custom variables. For more information about Vue using CSS custom variables, please pay attention to other related articles on 123WORDPRESS.COM!

You may also be interested in:
  • Detailed explanation of using defined variables to set CSS styles in Vue

<<:  MySQL 5.7.20 free installation version configuration method graphic tutorial

>>:  A brief introduction to Linux performance monitoring commands free

Recommend

Making a simple game engine with React Native

Table of contents Introduction Get started A brie...

mysql8.0.11 winx64 installation and configuration tutorial

The installation tutorial of mysql 8.0.11 winx64 ...

How to restore a single database or table in MySQL and possible pitfalls

Preface: The most commonly used MySQL logical bac...

Optimizing JavaScript and CSS to improve website performance

<br /> In the first and second parts, we int...

Let the web page redirect to other pages after opening for a few seconds

Just add the following code to achieve it. Method ...

Solve the problem of Navicat for Mysql connection error 1251 (connection failed)

Because what I wrote before was not detailed enou...

Detailed explanation of Vue3's sandbox mechanism

Table of contents Preface Browser compiled versio...

...

Detailed explanation of Mysql communication protocol

1.Mysql connection method To understand the MySQL...

How to create a Pod in Kubernetes

Table of contents How to create a Pod? kubectl to...

IIS configuration of win server 2019 server and simple publishing of website

1. First remotely connect to the server 2. Open S...