vue项目中在scss代码中使用data中的变量

尽管在日常开发中,这类情况实际上很少出现。

VUE2:

在HTML中使用时,请确保将cssVars绑定在需要使用CSS变量的元素或该元素的上层元素上。

<template>
  <div :style="cssVars">
    <div class="test"/></div>
  </div>
</template>

在data或者compute中给出前缀为--的css变量对象

computed: {
  cssVars() {
    return {
      '--color1': 'red',
      '--color2': 'blue'
    };
  }
}

在css代码中使用

<style lang="scss" scoped>
.test {
  /deep/ .el-form-item__label {
    color: var(--color) !important;
  }
}
</style>

vue3(v-bind CSS变量注入):

<template>
  <span> style v-bind CSS变量注入</span>
</template>
<script lang="ts" setup>
  import { ref } from 'vue'
  const color = ref('green')
</script>
<style scoped>
  span {
    /* 使用v-bind绑定组件中定义的变量 */
    color: v-bind('color');
  }
</style>

猜你喜欢

转载自blog.csdn.net/tt18473481961/article/details/134392303