vue通过props设置scss变量动态设置颜色

vue yekong 57℃

要将 this.color1 应用到 :deep(.echarts1Num) 中的 text-shadow 属性,你需要在 Vue 组件的 <style> 标签中使用 CSS 变量,并在组件的 mounted 钩子中动态设置这个变量的值。这样,你就可以将 this.color1 的值应用到 CSS 中,并且当 this.color1 的值发生变化时,页面上的样式也会相应地更新。

<div class="echarts1Title" ref="echarts1Title">
</div>

步骤 1: 在 <style> 中使用 CSS 变量

首先,在 <style> 标签中定义一个 CSS 变量,例如 --text-glow-color,并在 text-shadow 属性中使用这个变量:

<style lang="scss" scoped>
  .echarts1Info {
    // ... 其他样式

    :deep(.echarts1Num) {
      // ... 其他样式

      span {
        // ... 其他样式
        text-shadow: 0 0 10px var(--text-glow-color), 0 0 20px var(--text-glow-color);
      }

      .gsapNum {
        // ... 其他样式
        text-shadow: 0 0 10px var(--text-glow-color), 0 0 20px var(--text-glow-color);
      }
    }
  }
</style>

步骤 2: 在 mounted 钩子中设置 CSS 变量的值

然后,在组件的 mounted 钩子中,使用 JavaScript 来设置 CSS 变量 --text-glow-color 的值为 this.color1


  props: {
    color1: {
      type: String,
      default() {
        return ''
      }
    },
    color2: {
      type: String,
      default() {
        return ''
      }
    },
    name: {
      type: String,
      default() {
        return ''
      }
    },
    percent: {
      type: Number,
      default() {
        return 0
      }
    }
  },
mounted() {
  var that = this;
  const viewElem = document.body;
  // 监听窗口变化,重绘echarts
  const resizeObserver = new ResizeObserver(() => {
    setTimeout(() => {
      that.drawEcharts();
    }, 300)
  });
  resizeObserver.observe(viewElem);

  // 设置 CSS 变量的值
  this.$refs.echarts1.style.setProperty('--text-glow-color', this.color1);
},

步骤 3: 在 watch 中更新 CSS 变量的值

如果 color1 属性会在组件的生命周期中发生变化,你还需要在 watch 中监听 color1 的变化,并更新 CSS 变量的值:

watch: {
  color1(newVal) {
    this.$refs.echarts1.style.setProperty('--text-glow-color', newVal);
  },
  percent() {
    this.drawEcharts();
  },
},

完整的 mountedwatch 示例


  props: {
    color1: {
      type: String,
      default() {
        return ''
      }
    },
    color2: {
      type: String,
      default() {
        return ''
      }
    },
    name: {
      type: String,
      default() {
        return ''
      }
    },
    percent: {
      type: Number,
      default() {
        return 0
      }
    }
  },
mounted() {
  // ... 其他代码

  // 设置 CSS 变量的初始值
  this.$refs.echarts1.style.setProperty('--text-glow-color', this.color1);
},

watch: {
  color1(newVal) {
    // 当 color1 发生变化时,更新 CSS 变量的值
    this.$refs.echarts1.style.setProperty('--text-glow-color', newVal);
  },
  // ... 其他代码
},

这样,当 this.color1 的值发生变化时,页面上的 text-shadow 属性也会相应地更新为新的颜色值。

喜欢 (0)