How vue3 and vue2 use css variables (with the use of scss)

view 2:

Write css variables through inline styles (you can call variables in js), how to use css variables in style tags

//方式一 
<div
:style="`
--delay:${变量1}s;
--color:hsl(${变量2},50%,50%)
`"
> 

<div/>
//第二种方式
<template>
  <div :style="cssVars">
    <p class="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>

 It is recommended to write the second way of calculating attributes, when the value changes, it can also respond to changes

view 3:

Use v-bind directly in the style tag to bind variables in js 

<template>
  <div class="box">hello linge</div>
</template>

<script setup>
import { ref } from 'vue'
const color = ref('red')
</script>
<style>
.box {
  width: 100px;
  height: 100px;
  color: v-bind(color);
}
</style>
<template>
  <div class="box">hello linge</div>
</template>

<script setup>
import { ref } from 'vue'
const isActive = ref(true)
</script>
<style>
.box {
  width: 100px;
  height: 100px;
  background-color: v-bind('isActive?"red": "white"');
}
</style>

 The use of global css variables:

The official document introduces that  var(--global:xxx) global css variables can be used in this method (if scoped is used, the css variable will be automatically attached with a hash value), but only the writing method of css is introduced:

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

Writing in scss like this will cause an error to be compiled. After some exploration, if you want to use scss, please use the following method:

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

Scss dynamic value  #{} will automatically remove the double quotes, so as to get  var(--global:color) , solve the problem of compilation failure

Guess you like

Origin blog.csdn.net/m0_57033755/article/details/130502937