我可以从 VueJS 修改 CSS 变量吗?

Can I modify a CSS variable from VueJS?

CSS 模块让我们可以在 CSS 和 JS 中使用变量。

// use in temaplate
...
...<p :class="{ [$style.red]: isRed }">Am I red?</p>

// use in js 
...
...
<script>
export default {
    created () {
        console.log(this.$style.red)
        // -> "red_1VyoJ-uZ"
        // an identifier generated based on filename and className.
    }
}
</script>

/// use in css preprocessor
...
...
<style lang="stylus" module>
.red {
  color: red;
}
</style>

无论是模板、JS还是CSS我们都可以获取变量。但是,如果我们有一些功能,例如:单击并更改在 CSS.

中定义的所有网站的“主要颜色”

我们可以在JS中更改变量吗?

一个 CSS 模块是一个 CSS 文件,其中所有 class 名称和动画名称默认在本地范围内

所以当你想确保组件样式不会被覆盖时使用它们。

I am not sure what you asking for so I am assuming you want to dynamically change the css module class.

模板:

<template>
  <div>
   <div :class="[module]">I am a div</div>
   <button @click="make_blue_class">Make it blue</button>
   <button @click="make_red_class">Make it red</button>
  </div>
</template>

脚本:

  data: () => ({
    module_class: 'red'
  }),

  computed: {
    module: {
      get() {
        return this.$style[this.module_class]
      },
      set(new_class) {
        this.module_class = new_class
      }
    }
  },
  methods: {
    make_blue_class() {
      this.module_class = 'blue'
    },
    make_red_class() {
      this.module_class = 'red'
    }
  }

风格:

  .red {
    background: red;
  }
  .blue {
    background: blue;
  }

See it in action here