1

I want to separate the styles in a Vue.js component in modules. Each style module will have far more than just a class, and new classes will be added regularly. So, it will be hard to change the entire component's template. So, I'm looking for a more practical solution.

I came with the idea of, using a v-if in the styles, but not exactly sure how it should be implemented or if such thing is possible after all.

It will be way more practical, if just depending on the name sent with props, the entire styles changes.

<template>
  <div class="color-text">
    Text in the color of the class with just the name
  </div>
</template>

<script>
export default {
  name: 'comp',
  props: ['name']
}
</script>

<!-- General styles -->
<style scoped>
div{
  float: right;
}
</style>

<!-- red styles -->
<style module v-if="name === 'red'">
  .color-text{
    color: red;
  }
</style>

<!-- blue styles -->
<style module v-if="name === 'blue'">
  .color-text{
    color: blue;
  }
</style>

<!-- green styles -->
<style module v-if="name === 'green'">
  .color-text{
    color: green;
  }
</style>
1

1 Answer 1

1

If I was tackling this I'd use a transitive class value. and not worry about props at all.

<template>
  <div class="color-text">
    Text in the color of the class with just the name
  </div>
</template>

<script>
export default {
  name: 'comp'
}
</script>

<!-- General styles -->
<style scoped>
  div{
    float: right;
  }

  .red .color-text{
    color: red;
  }

  .blue .color-text{
    color: blue;
  }

  .green .color-text{
    color: green;
  }
</style>

then you can use the class property to pass in your color type

<div id="app">
    <comp class="red"></comp>
    <comp class="green"></comp>
    <comp class="blue"></comp>
</div>

I've put together an example jsfiddle though it may need some tweaking when it comes to scoped styles and how webpack handles the injection

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.