带有css模块的Vue - 在css和js之间传递变量

问题描述 投票:0回答:1

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中更改变量吗?

vue.js css-modules css-preprocessor
1个回答
0
投票

CSS模块是一个CSS文件,默认情况下,所有类名和动画名都在本地作用域

因此,当您想要确保不会覆盖组件样式时,请使用它们。

我不确定你要求什么,所以我假设你想动态改变css模块类。

模板:

<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

© www.soinside.com 2019 - 2024. All rights reserved.