'Use Vue variable in style section of a component
Is it possible to use a variable with the style tag of a component? Basically I have imported a mixin to my style tag that accepts 2 colors to create a gradient within a class. It works great but I want this dynamic so I can set it via a database. I understand I can bind a style via inline but a gradient for a div is rather long and works way better as a mixin.
component:
<template>
<section class="section" v-bind:class=" { 'color-section' : content.gradient_color_one }">
<div class="container">
<div class="columns">
<div class="column is-half">
<h2 class="is-size-4" v-html="content.title"></h2>
<div class="section-content" v-html="content.description"></div>
<a class="button" :href=" '/'+ content.button_link">{{ content.button_text }}</a>
</div>
<div class="column">
<img :src="content.image" :alt="content.title" />
</div>
</div>
</div>
</section>
</template>
<script>
export default {
props:[
'content'
],
}
</script>
<style lang="scss" scoped>
@import "../../sass/helpers/mixins";
.color-section{
color:red;
@include diagonalGradient( content.gradient_color_one , content.gradient_color_two);
}
</style>
mixins
@mixin diagonalGradient($top, $bottom){
background: $top;
background: -moz-linear-gradient(-45deg, $top 0%, $bottom 100%);
background: -webkit-gradient(left top, right bottom, color-stop(0%, $top), color-stop(100%, $bottom));
background: -webkit-linear-gradient(-45deg, $top 0%, $bottom 100%);
background: -o-linear-gradient(-45deg, $top 0%, $bottom 100%);
background: -ms-linear-gradient(-45deg, $top 0%, $bottom 100%);
background: linear-gradient(135deg, $top 0%, $bottom 100%);
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#92fe9d', endColorstr='#00c8ff', GradientType=1 );
}
Solution 1:[1]
You should use computed properties, as they probably are the best and cleanest way to achieve what you're trying to do. They also have a whole site about it on the Vue Docs:
https://vuejs.org/v2/guide/class-and-style.html
Basically, you COULD do something like this:
computed: {
style () {
return 'background: ' + this.top + ';' + '...'
}
}
Instead of passing the mixin, you could then pass the top and bottom variables. This is quite handy because in your computed style () function you have the freedom to do any javascript related stuff you want, so you can have conditionals, expressions and whatnot. Gives you powerful control over your style ;)
Solution 2:[2]
In Vue 3 you can now use v-bind
in single file component <style>
sections like this:
<style scoped>
.color-section {
color: v-bind('sectionColor');
}
</style>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | fweidemann14 |
Solution 2 | Maccesch |