Is there a way for me to retrieve SCSS color variables within the javascript of a Vue template?

I have a unique challenge in my application involving a component called Notification. To bring notifications to other components, I utilize the mixin method

toast('message to display', 'color-variable')
. My goal is to set the background color of my Notification component based on the 'color-variable'. The complication arises because these color variables are defined in a scss file. In the scss code, these colors can be accessed using the function color('color-name'), but I am unsure how to dynamically apply this scss function from the JavaScript within my Vue template.

My attempt at solving this involved using

:style="{'background-color': 
color(${notification.status})}", however, this approach did not yield the desired outcome. Is there a way to access scss variables as data directly within a view template?

Answer №1

Incorporating Sass variables into your Vue.js application can be highly effective, especially for theming purposes. Here's an illustration of how you can set up color variables in one of my applications:

$primaryShades: (
  50: #f5fef9,
  100: #e6fcf1,
  200: #d5fae8,
  300: #c4f8df,
  400: #b8f7d8,
  500: #abf5d1,
  600: #a4f4cc,
  700: #9af2c6,
  800: #91f0c0,
  900: #80eeb5,
  A100: #fff,
  A200: #fff,
  A400: #fff,
  A700: #f6fffa
);

$primary: map-get($primaryShades, 500);

$primary_100: map-get($primaryShades, 100);
$primary_200: map-get($primaryShades, 200);
$primary_300: map-get($primaryShades, 300);
$primary_400: map-get($primaryShades, 400);
$primary_500: map-get($primaryShades, 500);
$primary_600: map-get($primaryShades, 600);
$primary_700: map-get($primaryShades, 700);
$primary_800: map-get($primaryShades, 800);
$primary_900: map-get($primaryShades, 900);


$error: #ef9a9a;

$success: #76c078;

/* stylelint-disable -- exports for JS don't require style rules */
:export {
  primary: $primary;
  error: $error;
  success: $success;
}

@each $color, $value in $primaryShades {
  :export {
    primary#{$color}: $value;
  }
}

/* stylelint-enable */

To enable global access, import the variables using a global mixin in your app:

import colors from './assets/scss/colors_vars.scss';// Update path as needed

// Inside global mixin
Vue.mixin({
  data() {
    return {
      colors: colors
    };
  }
})

Then simply access these variables in your code like any other data:

toast('message to display', this.colors.error) // Using the error color in this example

You can write logic to dynamically determine and apply the right color when needed:

computed: {
   notificationColor() {
     if(errorCondition) {
      return this.color.error
    }
     if(successCondition) {
      return this.color.success
    }
  }
}

If you have defined color arrays, refer to how they can be looped over and exported in the Sass block. Accessing primary shade 50 would look like this.colors.primary50. This allows you to maintain color settings in your styles while seamlessly utilizing them in JavaScript and updating them centrally.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Challenges arise when using scoped styles and deep styling in the context of Vue 3

Struggling with styling a child component from its parent in vue3 and encountering difficulties. In this scenario, I have created a generic button with predefined CSS properties and now attempting to customize this button from another component. Parent C ...

Attempting to install puppeteer within the Visual Studio Code terminal with financial support

I am having trouble installing puppeteer using the VSC terminal. Every time I try to run the npm install command, it doesn't download and prompts me about funding. Can someone please assist me with this issue? npm i puppeteer up to date, audited 67 p ...

The implementation of a custom event for jQuery rows is not functioning as expected

I need assistance with jQuery code to add click events only to columns in a row that have text in the first column. Specifically, I want to hide rows containing "1/" in the first column when clicked on for the first row. <table class="results"> < ...

Chrome's rendering of CSS flex display shows variations with identical flex items

I am facing an issue with my flex items where some of them are displaying incorrectly in Chrome but fine in Firefox. The problem seems to be with the margin-right of the rectangle span within each flex item, along with the scaling of the text span due to f ...

``motioning a component beneath another component that may be in a state

Having an issue with my CSS. I have some elements generated by JavaScript and when hovering over them, another element is displayed below the others for some reason. Here's the CSS related to this problem: .hiddenTextjob { display:none; ...

What is preventing me from utilizing middleware in my express route?

I have a project in progress where I am developing an API. As part of this process, I need to implement a user system and ensure secure access to the API. Below is the middleware function used for validation: 'use strict' const jwt = require(& ...

Unlock the full potential of vue-form-generator by integrating cleaver.js for enhanced functionality

When using VueFormGenerator with cleaver.js, I encountered an issue after adding the code below (as per the documentation) which resulted in the error message "Unknown custom element: ". cleaver.js was installed via npm. { type: "cleaver", inputType ...

Modify the styling of the input file in HTML to bind it with a

My file input setup looks like this; <input type="file" id="restoreFile"> To customize the appearance, I first set display: none; and created a label for the "restoreFile" input styled as a button. When I click the label (button) ...

I am currently exploring React Router, but I am struggling to grasp this particular behavior

My Express server serves the Create-React-App build. When I access http://localhost:8000/ while the server is listening, my page loads correctly. However, if I reload the page or navigate directly to it from the navigation bar, instead of seeing the UI, pl ...

Looking to integrate the date, month, and year selection tags into the inline format

The Edit User Profile page includes a Birthday field, which is currently displayed vertically. I am looking to change the layout so that the Birthday field appears horizontally. Here is the code I am using: Within visitors/edit.html.erb, <%= simple_f ...

Creating mutual reactivity between two inputs in Vue.js

I am in the process of creating a tool that calculates the cost of purchasing specific materials. One challenge I'm facing is that users sometimes buy by mass and other times by volume. My goal is to have two active input fields (one for mass and one ...

Using JQuery to Execute Matching Based on Text Within <A> Elements

After reviewing the resources on Jquery Extract URL from Text and jquery match() variable interpolation - complex regexes, I am still a bit confused. The issue at hand is that I have a webpage with a dropdown menu at the top. Inside the dropdown, there ...

Grab all the text using Java Jsoup

I am having an issue with the code I have written. The doc.body.text() statement is not displaying the text content within the style and script tags. I examined the .text() function code and found that it searches for all instances of TextNode. Can someone ...

What is the best way to adjust the decimal values in my API calls?

Is there a way to adjust the numerical data returned by the API to display only two decimal places instead of three? For example, if the number is 140.444, I want it to show as 140.44 What changes do I need to make? function fetchData() { fetch(" ...

Tips for generating an ordered list that begins with 01

Currently, I am developing a Ruby on Rails application in which I am iterating over the tuto. .container .row .col-xs-12.col-sm-12 h1.text-gray Tutorials br .col-xs-10.col-sm-5.index-background - @tut ...

Basic inquiry about Ajax

Would you like to know a simple solution for refreshing a specific area of your website using ajax? Instead of having JavaScript constantly checking for changes on the server, is there a way for the server to send data when a certain event occurs? Imagine ...

Unspecified reference to this.$refs.canvas in Vue.js

Currently working on a new project that involves using vuejs3 and canvas, but encountering some issues with the canvas element. Any suggestions or ideas would be greatly appreciated! Within my project, I am receiving undefined when trying to access this.$ ...

Clicking on the input triggers the appearance of a border using the OnClick function

I am currently developing my own website with a login feature that requires input tags of text-type. I would like to implement a functionality where clicking on these input tags will display a border, even when the mouse is not directly hovering over them. ...

Trouble with disabling default actions and transferring text

When the user clicks on loginAccount, the intention is to extract the text from the element with the id input-1 and assign it to username. This same process should occur for password, followed by form submission. However, despite using e.preventDefault() ...

Experience the impact of a lagging network connection on Chrome extensions through the power of React-NextJS

I'm currently working on a Chrome extension that requires me to limit download speeds in the browser programmatically (client-side). Despite researching extensively on the subject, I have not been able to find any information on how to achieve this us ...