【问题标题】:How to get CSS Modules to work in Vue class binding?如何让 CSS 模块在 Vue 类绑定中工作?
【发布时间】:2020-07-25 12:50:54
【问题描述】:

Google 已经帮不了我了。

我在 Vue 中有这样的模板:

<template>
    <button
        :class="{ 'button-selected': isSelected }">
    </button>
</template>

在我尝试使用 CSS 模块之前,一切都很好:

<template>
    <button
        :class="{ styles['button-selected']: isSelected }">
    </button>
</template>

...

import styles from "./Button.scss"

...

data () {
    return {
        styles
    }
}

当然。我不能使用它,因为

let obj = { style['button-selected']: this.isSelected }

也是无效的表达方式。

我找到了临时解决方案:

<template>
    <button
        :class="classes">
    </button>
</template>
...
computed: {
    classes () {
        let obj = {}
        obj[this.styles['button-selected']] = this.isSelected
        return obj
    }
}

但由于我使用这种模式,我需要为每个元素创建一个计算属性。
我正在尝试另一种方法。

提前感谢您的帮助。

【问题讨论】:

    标签: javascript css vue.js vuejs2 vue-component


    【解决方案1】:

    你可以使用 es6 computed property 名称:

    <button :class="{ [styles['button-selected']]: isSelected }">
    

    styles['button-selected'] 周围的外括号将该表达式评估为属性名称。

    new Vue({
      el: "#app",
      data() {
        return {
          isSelected: true,
          styles: {
            'button-selected': 'redclass'
          }
        }
      }
    });
    .redclass {
      background: red;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
    <div id="app">
      <button :class="{ [styles['button-selected']]: isSelected }">
      asdf
      </button>
    </div>

    你也可以使用三元:

    <button :class="isSelected ? styles['button-selected'] : ''">
    

    【讨论】:

    • 这太容易了!谢谢!
    猜你喜欢
    • 2018-08-03
    • 1970-01-01
    • 2019-01-12
    • 1970-01-01
    • 2021-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多