Using JS variables in CSS in vue2 / vue3 (SCSS also applies)

IL Fengzi 2021-09-15 09:40:02

Preface

In many cases, we need theme matching , Or unified and convenient management ,css Variables are essential . stay Vue Lieutenant general data Variables in reflect css Variables are also the general trend . About css The introduction of variables can be viewed MDN , For compatibility issues, see Can I use

Vue2 usage

In the past Vue2 in , We usually use computational properties to reflect data Medium Variable to css in :

<template>
<div :style="cssVars">
<p class="text"> Test text </p>
</div>
</template>
<script> export default { data() { return { color: "red" }; }, computed: { cssVars() { return { "--color": this.color }; } } }; </script>
<style lang="scss" scoped> .text { color: var(--color); } </style>
 Copy code 

Thus in data When the data in changes , The calculation properties will also be changed synchronously and reflected to the mounted node  style  in .

Vue3 usage

stay Vue3 in , Provides a new shortcut :

<template>
<div>
<p class="text"> Test text </p>
</div>
</template>
<script> export default { data() { return { color: "red" }; } }; </script>
<style scoped vars="{ color }"> .text { color: var(--color); } </style>
 Copy code 

Through here On the label vars To deconstruct data , So you can use... In the style area css The variable !

documentation :sfc-style-variables

compatible scss

In the official documents  var(--global:xxx)  In this method, you can use global css Variable ( If you use scoped Will automatically give css Variable with hash value ), But it only introduces css Writing :

<style scoped vars="{ color }">
h1 {
font-size: var(--global:fontSize);
}
</style>
 Copy code 

It's written in scss It will compile and report errors . Feel for it , If you want to use scss , Please write as follows :

<style lang="scss" scoped vars="{ color }">
.home {
color: var(#{"--global:color"});
}
</style>
 Copy code 

summary

No matter in Vue2 still 3 in ,css Variables are reflected immediately , Don't worry about problems that won't be updated .

although Vue3 Medium css Variables are simple , But at the moment   experimental  :

If you pursue stability , No matter in Vue3 still 2 in , It is recommended to use the writing method of calculated attributes .

Please bring the original link to reprint ,thank
Similar articles

2021-09-15