Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional stylesheet in .vue component

I'm working with vue component (cli .vue)

I need to have my stylesheet appear only if certain boolean is true/false. Simplest explanation would be something like : When myVar==false, component is not loading styles.

<style v-if="myVar" lang="scss"> @import 'mystyles.css' </style>

I know it is impossible in that way, but how I'm able to do 'similar' thing?

I need to load my styles in vue if user want to use default Styles, if not I need to prevent them from being loaded.

My component is used not once but many times in page, but that condition of using/not using default css need to be apply by all components as well, so no problem here.

Any ideas? Thanks for help or any ideas in advance :)

like image 394
Krzysztof Skorupski Avatar asked Dec 19 '17 19:12

Krzysztof Skorupski


People also ask

Does V-if destroy component?

v-if is "real" conditional rendering because it ensures that event listeners and child components inside the conditional block are properly destroyed and re-created during toggles.

How do I add styles to Vue component?

In Vue. js, we can add an inline style to our element by binding the style attribute in the HTML tag. For reference, :style is shorthand for v-bind:style . Inline styling can be done in two ways: using object syntax or array syntax.

How do I add conditional classes to Vue?

To conditionally apply a CSS class at runtime, you can bind to a JavaScript object. To successfully complete this task, you must complete two steps. First, you must ensure that your CSS class is defined. Then, you create the class bindings in your template.

What is the difference between V-if and V show?

The key difference is that v-if conditionally renders elements and v-show conditionally displayselements. This means that v-if will actually destroy and recreate elements when the conditional is toggled. Meanwhile, v-show will always keep the element in the DOM and will only toggle its display by changing its CSS.


1 Answers

Using SCSS, you can wrap that CSS in a class, something like this:

<style lang="scss">

.conditional-class {
    @import 'stylesheet.scss';
}

</style>

And then use a Vue class binding for that class:

<div :class="{ conditional-class: true }">
    ...
</div>

This way the CSS won't apply unless the class is active on that element. If you want the styles to apply all over the app, then put that class on the app root element.

like image 160
maxpaj Avatar answered Sep 22 '22 05:09

maxpaj