Is it possible to change a CSS variable using VueJS?

With CSS Modules, we are able to utilize variables in both our CSS and JS code.

// Using it in template
...
...<p :class="{ [$style.red]: isRed }">Am I red?</p>

// Using it in JS 
...
...
<script>
export default {
    created () {
        console.log(this.$style.red)
        // -> "red_1VyoJ-uZ"
        // This is an identifier generated based on the filename and className.
    }
}
</script>

/// Using it in a CSS preprocessor
...
...
<style lang="stylus" module>
.red {
  color: red;
}
</style>

We can access the variable regardless of whether it's being used in the template, JS or CSS. However, what if we want to implement a feature where clicking changes the website's overall 'main-color' that is defined in CSS?

Is it possible to modify the variable in JS?

Answer №1

A CSS Module is a unique type of CSS file that ensures all class names and animation names are contained locally by default.

Utilize CSS Modules when you need to guarantee that a component's style will not be overridden.

If you're unsure about what you're asking for, it seems like you want to dynamically modify the CSS module class.

Here's a simple template:

<template>
  <div>
   <div :class="[module]">I am a div</div>
   <button @click="make_blue_class">Make it blue</button>
   <button @click="make_red_class">Make it red</button>
  </div>
</template>

And here's the script section:

data: () => ({
    module_class: 'red'
  }),

  computed: {
    module: {
      get() {
        return this.$style[this.module_class]
      },
      set(new_class) {
        this.module_class = new_class
      }
    }
  },
  methods: {
    make_blue_class() {
      this.module_class = 'blue'
    },
    make_red_class() {
      this.module_class = 'red'
    }
  }

Finally, add some styling:

.red {
    background: red;
  }
  .blue {
    background: blue;
  }

To see this in action, click on the following link: CSS Module Example

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

Utilizing jQuery's onclick and onchange events on multiple elements

In my current setup, there is a select menu with two arrows for adjusting the values (+/-). Presently, I have a function set to trigger when the arrows are clicked, updating the value in the select. However, I now want to add another function that will upd ...

Submitting form data to PHP without refreshing the page

I've been attempting to send form data, specifically an array, to a PHP file without having the page refresh. I've implemented AJAX for this purpose but it doesn't appear to be working as intended. Below you'll find the syntax of the fo ...

jPages fails to recognize dynamically added images using jQuery in real-time

I have a HTML and JS script that is designed to load images from PHP using AJAX and then place them into a div. Afterwards, a JavaScript function will paginate the images. Everything works perfectly fine when I hardcode the images manually. However, when I ...

Creating a specialized .toString() function for an array

When trying to create a custom .toString() method on the Array prototype, how can you access the actual array that the method is called on? This approach seems to work: Array.prototype.toString = () => 'custom'; "" + [1,2,3]; // 'custom ...

How to Customize the Size and Color of secureTextEntry Inputs in React Native

When it comes to styling a password input like the one below: <TextInput name="Password" type="password" mode="outline" secureTextEntry={true} style={styles.inputStyle} autoCapitalize="none" autoFocus={true} /> I also ap ...

Having trouble setting permissions with Node ACL?

Struggling to determine how to assign user roles and permissions using Node ACL as a newbie in the MEAN stack. I still haven't grasped the workings of node or javascript framework. The goal is to implement a registration system where newly registered ...

Component re-rendering and initializing useReducer

I made some revisions to this post. Initially, I shared the entire problem with my architecture and later updated it to focus directly on the issue at hand in order to make it easier for the community to provide assistance. You can now jump straight to the ...

How to set focus on a TextField in NativeScript Vue

I'm currently working with NativeScript ("nativescript-vue": "^2.5.0") and testing on iOS 13 "tns-android": { "version": "6.0.0" }, "tns-ios": { "version": "6.0.1" } I am attempting to focus on a TextField when a button is t ...

Troubleshooting: Fullscreen Video Autoplay Issue in Angular HTML

Could someone shed some light on why this autoplay video isn't working properly in Chrome? The video is actually hosted in firebase storage. Interestingly, it plays fine when you navigate to a different page and then return to the homepage, but doesn ...

The Nuxt loading progress bar keeps appearing and disappearing repeatedly

While the default nuxt loading bar is effective on simple pages, I encountered an issue when making multiple axios requests where the progress bar would load each time a request was sent. I needed the progress bar to recognize all these requests as a singl ...

The download button consistently targets and downloads the initial SVG in my collection. How can I configure it to target each individual SVG for download?

I'm currently working on a QR code app using React. The goal is for users to submit a form with a value, which will then generate an SVG QR code that can be downloaded. However, I'm running into an issue where the same SVG file is being downloade ...

Operating the VueJS toggle feature on a checkbox

I'm curious about the best way to implement a function toggle using a checkbox in VueJS. <input v-model="discount" type="checkbox" name="discount"> My goal is to update a string in my view when the discount checkbox is checked, displaying the ...

Building a contact form in Angular and sending emails with Nodemailer

Currently, I am in the process of setting up a contact form for my website. Since I am utilizing a MEAN stack, it made sense to incorporate the nodemailer module for sending emails. In order to handle this functionality, I have established an endpoint &ap ...

What are the best scenarios for utilizing (a)synchronous calls?

Currently, I am working on a project for my office as a learning exercise. We have a tradition of bringing food every Monday, so I decided to create a program that displays each person's turn. My webpage can generate a calendar with a spare color colu ...

Updating a computed property in Vue.js after an asynchronous computed property has been updated

I'm currently facing an issue with updating a computed property (filteredSyms) that relies on an asynchronous computed property (allSynonyms). To handle this, I am utilizing the async-computed plugin available at: https://www.npmjs.com/package/vue-as ...

Press the 'enter' button to post your tweet with Greasemonkey

I am working on a Greasemonkey script that will automatically submit a tweet when the user presses the 'enter' key. The script works perfectly on a basic HTML page with some help from tips I found on this website. However, when I attempt to use t ...

Converting data into a multidimensional array in AngularJS: A comprehensive guide

Struggling to convert a JSON array into a multidimensional array, looking for some guidance. I attempted using _.groupBy in underscore.js, but it's not proving successful with the nested array. If there is any way to convert from the given data [{ ...

Filtering rows of an HTML table that contain links in the `<href>` column data in real time

When using HTML and JavaScript, I have found a solution that works well for many of the columns I am working with. You can see the details on how to dynamically filter rows of an HTML table using JavaScript here. var filters=['hide_broj_pu',&apo ...

Unable to send State from parent Component to Child (state counter for pomodoro clock)

Hi everyone, I am relatively new to React and currently working on building a Pomodoro Clock. However, I have hit a roadblock while trying to get the buttons + and - to update the numbers set in my State. Here is what I have in my Main App Component: clas ...

Can you provide an example of JSON for a MultiStep Form that includes a variety of control types for viewing

Could someone please provide me with JSON examples of multi-step forms that include various types of controls such as radio buttons, checkboxes, dropdown menus, and calendars? I am in need of JSON for both the view and edit forms. Your help would be grea ...