Search code examples
laravelsassvue.jslaravel-elixir

Using sass variables in a VueJS component


I got a rather simple problem with a VueJS component that needs to use a variable. The problem comes with getting sass to register variables inside a component.

I tried importing the _variables.scss file containing my variables but to no luck. At this point any guidance is very much appreciated, or if there is another way for a component to inherit styling.

MyComponent.vue

<template>
    <div class="my-color"></div>
</template>
<style lang="sass">
    .my-color {
        color: $primary-color;
    }
</style>
<script>
    export default{
        data(){
            return {}
        }
    }
</script>

Gulpfile.js

var elixir = require('laravel-elixir');
require('laravel-elixir-vueify');

elixir(function(mix) {
    mix.browserify('main.js');
    mix.sass('app.scss');
});

app.scss

@import "node_modules/bootstrap-sass/assets/stylesheets/bootstrap";
@import "modules/variables";

variables.scss

$primary-color: #BA2731; //Red

Solution

  • Importing the _variables.scss in every component seems to be the only solution I've found so far (it should work, according to this issue).

    <template>
        <div class="my-color"></div>
    </template>
    <style lang="sass">
        @import 'path/to/your/_variable.scss'; // Using this should get you the variables
        .my-color {
            color: $primary-color;
        }
    </style>
    <script>
        export default{
            data(){
                return {}
            }
        }
    </script>
    

    As you are only going to include variables, this shouldn't be a problem.

    But as mentioned in the issue, a word of caution: You should only include abstract entities (variables, extends, mixins) into every component, no concrete CSS rules.