Home > Blockchain >  Can I use v-if with style tag to choose a different source file? Or is there a better alternative?
Can I use v-if with style tag to choose a different source file? Or is there a better alternative?

Time:05-23

I tried doing the example below, but it would not work. The reason why I am trying to do this is is that I would have to add way too many modifiers (--tuned) to make this work. So I was trying to source the css file based on a condition. Why would this not work and does anyone know if there is a better alternative that a million modifiers?

<style v-if="!isTuningActive" lang="scss" src="./normal-version.scss"></style>
<style
  v-else
  lang="scss"
  src="./tuned-version.scss"
></style>

CodePudding user response:

Why not separate into components? Each components with his own styling.

https://vuejs.org/guide/essentials/component-basics.html

CodePudding user response:

You can compile your separate scss files into a single stylesheet (main.scss for example), then just import that main.scss file into your parent component (likely, App.vue).

This will allow you to simply switch the css class on your example above instead of trying to conditionally import stylesheets.

For example, lets say your new 'main.scss' file contains the following scss.

.tuned-version {
   p { color: red }
}

.untuned-version {
   p { color: blue } 
}

Then you'll simply need to dynamically add the class depending on your isTuningActive property.

<div :>
    <p>My content</p>
</div>

Helpful references:

  1. Compiling scss in Vue: https://vue-loader.vuejs.org/guide/pre-processors.html#sass
  2. Dynamic class binding: https://vuejs.org/guide/essentials/class-and-style.html#binding-html-classes
  • Related