vue3和vue2 使用css变量的方法(附带scss的使用方式)

vue2:

通过内联样式写css变量(可以调用js里面的变量),如何在style标签里面就可以使用css变量

//方式一 
<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>

 建议写成第二种这种计算属性的方式,当值发生改变,也可以响应变化

vue3:

直接在style标签里面使用v-bind绑定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>

 全局的css变量的使用:

官方文档中介绍以 var(--global:xxx) 在这种方法可以使用全局的 css 变量(若使用 scoped 会自动给 css 变量附带 hash 值),但只介绍了 css 的写法:

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

这么写在 scss 是会编译报错的。摸索一番,如果要使用 scss ,请使用如下写法:

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

scss 动态取值 #{} 会将双引号自动去掉,从而得到 var(--global:color) ,解决了编译失败的问题

猜你喜欢

转载自blog.csdn.net/m0_57033755/article/details/130502937
今日推荐