Why my css variables don't work in my Vue component using sass?

Viewed 44

I am using sass with vue version-3. In one of my components I have this code:

HelloWorld.vue :

<template>
  <div class="greetings">
    <h1>{{ msg }}</h1>
    <h3>
      You’ve successfully created a project with
      <a href="https://vitejs.dev/" target="_blank" rel="noopener">Vite</a> +
      <a href="https://vuejs.org/" target="_blank" rel="noopener">Vue 3</a>.
    </h3>
  </div>
</template>

<script setup>
defineProps({
  msg: {
    type: String,
    required: true
  }
})
</script>

<style scoped lang="scss">
@use "sass:list";
@use "@/assets/sass-folder/variables";
@use "@/assets/sass-folder/main";
h1 {
    color: list.nth(variables.$theme-lighten-1, 2);
}
    
h3 {
  color: var(--blue);
}

</style>

In that component I inserted a main.scss file with the help of @use sass command. But the css variable --blue is not recognized by this component. This is the code of main.scss file:

main.scss :

:root {
  --blue: #1e90ff;
  --white: #ffffff;
}

//h3 {
//    color: red;
//}

If I un-comment the h3 styles in that file, the color of h3 tag in my component becomes red, so the file is imported correctly. Could anyone please help me which part of my codes is wrong that --blue variable is not recognized in HelloWorld.vue component?

1 Answers

Option 1: The problem might be with how you use Scss

I've never worked with @use before. If I hook up your HelloWorld.vue with your main.scss the way I'm used to, your blue variable works. My standard way is to have a main.ts or main.js file. That file has just a few lines of code:

import { createApp } from "vue";
import App from "./App.vue";
import "./assets/main.scss";

Option 2: The problem might be with the Scss itself

I would try mixing local <style scoped> and global <style> styles. Second, if that doesn't work, I'd try with a deep selector :deep() in my scoped style. Lastly, I'd try having my blue and white variables in the variables file instead of main.

I hope one of these options sends you the right direction.

Related