Search code examples
vue.jsvue-cli-3

Combine several CSS classes into one


In a Vue project I want to combine a few css classes that I use on two elements in order to declutter my html. I was told I can do something like this with the cli, however i have no idea how.

.common-class {
  @apply .class1 .class2 ...;
}

Solution

  • You can always create a computed property that returns those two classes combined:

    new Vue({
      el: "#app",
      computed: {
        combineStyles() {
          return 'foo bar'
        }
      }
    })
    .foo {
      color: red;
    }
    
    .bar {
      font-size: 2rem;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
    
    <div id="app">
      <p :class="combineStyles">foo bar</p>
    </div>

    No CSS preprocessor needed. However if you want to use some CSS preprocessor then follow the docs.