Vue3 JS and SCSS variables use each other

During development, you will encounter the following requirements:

  1. Using SCSS variables in JS. For example, if a color is defined in scss and the el-menu component uses this color as the background color, you need to obtain the scss variable and pass the variable value to the el-menu component through the background-color attribute (of course you can also use it in JS Redefine a variable to store the color).
  2. Using JS variables in SCSS. For example, with the dynamic skin-changing function, if the user selects a certain color as the theme color, the theme color of the entire system will be switched to this theme color. The color selected by the user is stored in a JS variable, and SCSS needs to use the color stored in the JS variable. Similar scenes include dark mode, etc.

This article provides ideas for solving the above problems.

1 JS uses SCSS variables

1.1 Create SCSS variable file

Create a scss directory under the src directory , which stores scss files. It should be noted here that if JS wants to use variables defined in SCSS files, in vue3, the SCSS file name format for storing variables is xxx.module.scss .

Such as variables.module.scss . Different from vue 2.x, the .module here cannot be omitted. In vue 2.x, the file name is not required to use xxx.module.scss .

Created in the src/scss/ directory

config.module.scss file, which is used to define scss variables:

$titleColor: #FF0000;

1.2 Export SCSS variables

There is a variable defined in the config.module.scss file created above : $titleColor .

If we only use it in the style tag of other scss files or vue files , we only need to use @import to introduce config.module.scss in the corresponding file . But if you need to use it in JS/TS in script , you also need to export the variables you need to use through export :

$titleColor: #FF0000;

:export {
  titleColor: $titleColor;
}

This will export the value of $titleColor to JS/TS through the variable name titleColor .

1.3 Using SCSS variables

If you want to use the above variables in the script of the vue file , first import the scss file:

import config from '@/scss/config.module.scss'

The value of config is the object of scss file :export . Output config object:

console.log(config)

Console output:

{
    
    titleColor: '#FF0000'}

At this point, you can get the value of $titleColor in the scss file through config.titleColor .

The vue code is as follows:

<template>
  <div>
    <h1 :style="{color: color}">JS 获取 SCSS 变量值</h1>
  </div>
</template>

<script lang="ts" setup>
import {
      
       ref } from 'vue'
import config from '@/scss/config.module.scss'

const color = ref(config.titleColor)
</script>

2 CSS variables

Before discussing the use of JS variables in SCSS code, we need to talk about CSS variables in CSS Next. Most of my friends are familiar with CSS 2 and CSS 3, and CSS Next is nothing new. One of the most powerful capabilities of CSS Next is CSS variables.

2.1 Global CSS variables

We can create the test.css file in the src/scss directory above to try using css variables.

:root {
    
    
  --bgColor: pink;
}

body {
    
    
  background-color: var(--bgColor);
}

Global CSS variables are defined in :root . The naming convention of CSS variables starts with two -. A global CSS variable is defined above, and the variable name is –bgColor .

When using variables, use the CSS var() function.

Introduce this file in main.ts :

import '@/scss/test.css'

At this time, you can see that the background color in the browser turns pink.

2.2 CSS variables within components

CSS variables can also be used in components. Just define the variable in the corresponding selector.

<template>
  <div class="demo">
    <div class="css-div">CSS 变量</div>
  </div>
</template>

<script lang="ts" setup>
</script>

<style scoped lang="scss">
.demo {
      
      
  --font-size: 30px;

  .css-div {
      
      
    --textColor: blue;

    font-size: var(--font-size);
    color: var(--textColor);
  }
}
</style>

With the foundation of CSS variables, we can now discuss how to use JS variables in scss.

3 SCSS uses JS variables

We use a demo to illustrate how to use js variables in scss: there are three buttons and a div. Clicking the three buttons will switch the background color and text color of the div.

3.1 Basic code

First implement the basic code of the page:

<template>
  <div class="demo">
    <button v-for="(item, index) in btns"
            :key="index"
            @click="onBtnClick(item.bgColor, item.textColor)"
    >{
   
   { item.title }}</button>

    <div>
      <div class="example">Hello World</div>
    </div>
  </div>
</template>

<script lang="ts" setup>
const btns = [
  {
      
       title: '红色主题', bgColor: '#FF9191', textColor: '#FF0000' },
  {
      
       title: '蓝色主题', bgColor: '#B3C4FF', textColor: '#042BA9' },
  {
      
       title: '默认主题', bgColor: '#333333', textColor: '#FFFFFF' }
]
const onBtnClick = (bgColor: string, textColor: string) => {
      
      
  console.log(bgColor, textColor)
}
</script>

<style scoped lang="scss">
.demo {
      
      
  padding: 10px;

  .example {
      
      
    --textColor: #FFFFFF;
    --bgColor: #333333;

    display: inline-block;
    margin-top: 20px;
    font-size: 20px;
    padding: 20px 50px;
    color: var(--textColor);
    background: var(--bgColor);
  }
}
</style>

The page is as follows:

image-20221016172352073

The above code is relatively simple. The btns variable defines three buttons and displays the three buttons through v-for . When clicking the button, pass the two parameters bgColor and textColor to the click event onBtnClick function. Display the div of Hello World , and control the background color and text color through the two variables -textColor and -bgColor .

The next step is to use different text colors and background colors when clicking different buttons.

Vue3 provides two ways to dynamically change css variables. The following two methods are implemented based on the above basic code:

3.2 Method 1: setProperty

Vue provides setProperty method to change CSS variables.

  1. Add the ref attribute to the target div:
<template>
		...
    <div>
      <div class="example" ref="exampleRef">Hello World</div>
    </div>
  </div>
</template>
  1. Get the reference ( ref ) to the div :
import {
    
     ref } from 'vue'

const exampleRef = ref<HTMLDivElement | null>()
...
  1. Call the setProperty method that references the style attribute :
<script lang="ts" setup>
...
const onBtnClick = (bgColor: string, textColor: string) => {
      
      
  if (exampleRef.value) {
      
      
    exampleRef.value?.style.setProperty('--textColor', textColor)
    exampleRef.value?.style.setProperty('--bgColor', bgColor)
  }
}
</script>
...

3.3 Method 2: v-bind

Vue3 provides the v-bind function for the style of vue files , which enables binding JS/TS variables to CSS variables.

  1. Define two variables in TS to store the two parameters passed when clicking the event:
const currentBgColor = ref('#333333')
const currentTextColor = ref('#FFFFFF')
  1. The midpoint parameters of the click event are assigned to the above two variables:
const onBtnClick = (bgColor: string, textColor: string) => {
    
    
  currentBgColor.value = bgColor
  currentTextColor.value = textColor
}
  1. Use v-bind in style to bind the above two JS variables :
.demo {
	...

  .example {
    --textColor: v-bind(currentTextColor);
    --bgColor: v-bind(currentBgColor);

    ...
    color: var(--textColor);
    background: var(--bgColor);
  }
}

Use the above two methods according to your own preferences. You can try to implement functions such as theme switching and dynamic skin changing based on the above ideas. We will continue to discuss this topic in the following practical series of articles.

Thank you for reading this article. If this article has given you a little help or inspiration, please support it three times, like, follow, and collect. The author will continue to share more useful information with you.

Guess you like

Origin blog.csdn.net/youyacoder/article/details/127364009