Adding a class to a Vue component using the $refs property

I am facing an issue where I need to add dynamic class names to various Vue components based on their reference names listed in a configuration file. Manually adding classes to each component is not feasible due to the large number of components.

To address this, I attempted to locate each component using the `$refs` property and then dynamically add the desired class to the element's class list. However, I noticed that the added class gets removed as soon as there is any user interaction with the component (e.g. clicking on it or updating its value).

Below is a snippet of the code that I experimented with:

beforeCreate() {
    let requiredFields = config.requiredFields
    this.$nextTick(() => {
        requiredFields.forEach(field => {
            if(this.$refs[field]) {      
                this.$refs[field].$el.classList.add('my-class')
            }
        })
    })
}

Answer №1

Here is a solution you can implement:


document.querySelector('.my-class').classList.add('new-class');

Answer №2

Although it's been a while since this question was originally posted, I recently came across an easier method for adding a class to $refs while experimenting with something similar.

If we reference

this.$refs['some-ref'].$el.classList
, we are working with a DOMTokenList that provides various methods and properties that can be utilized.

In this case, adding a class is straightforward:

this.$refs['some-ref'].$el.classList.add('some-class')

Answer №3

Ensure that your config.requiredFields includes the reference name as a string, no more and no less, with the following code snippet:

   // Loop through each ref
    for (let ref in this.$refs) {
        config.requiredFields.push(ref)
     }
   // Resulting config.requiredFields array: ['one','two]

Here is an illustrative example:

Vue.config.devtools = false;
Vue.config.productionTip = false;

Vue.component('one', {
  template: '<p>component number one</p>'
})
Vue.component('two', {
  template: '<p>component number two</p>'
})

new Vue({
  el: "#app",
  beforeCreate() {
    let requiredFields = ['one','two'] //  config.requiredFields should be like this
    this.$nextTick(() => {
        requiredFields.forEach(field => {
            if(this.$refs[field]) {      
                this.$refs[field].$el.classList.add('my-class')
            }
        })
    })
}
})
.my-class {
  color : red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <one ref="one" ></one>
  <two ref="two" ></two>
</div>

Answer №4

It is important to ensure that classList.value is in array format as it defaults to a string.

methods: {
    handleClick(reference) {
      const activeClass = 'active-submenu'
      if (!this.$refs[reference].classList.length) {
        this.$refs[reference].classList.value = [activeClass]
      } else {
        this.$refs[reference].classList.value = ''
      }
    },
  },

Answer №5

This solution provided me with great assistance. I was faced with the challenge of targeting an element within a v-for loop and devised a small method to address it (utilizing Quasar/Vue). I hope this helps others save time just as it did for me.

applyStyleToReference: function(refElement, positionIndex, styleClass) {
            //This function adds a specified CSS class to a $ref element, even within a v-for loop.
            //Provide the $ref name (refElement - text), index in the list (positionIndex - integer), and css class name (styleClass - text).
            
            if (this.$refs[refElement][positionIndex].$el.classList.value.includes(styleClass)) {
                console.log('Class already applied');
            } else {
                this.$refs[refElement][positionIndex].$el.classList.value += ' ' + styleClass;
            }  
        }

Answer №6

const selectedTag = this.$refs[ref-key][0];
$(selectedTag).addClass('d-none');

To hide a specific tag, first retrieve it by using ref like

let selectedTag = this.$refs[ref-key][0];
. Then, convert the tag into a jQuery object using
$(selectedTag).addClass('d-none');
to add the 'd-none' class and hide the tag.

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

The drawing library (Google Maps) failed to load

I am looking to integrate drawing mode into Google Maps for my project. Below is the code snippet from my View: <!DOCTYPE html> <html> <head> <meta name="viewport" content="initial-scale=1.0, user-scalable=no"> <me ...

Adjusting color of fixed offcanvas navbar to become transparent while scrolling

After creating a navbar with a transparent background, I am now using JavaScript to attempt changing the navigation bar to a solid color once someone scrolls down. The issue is that when scrolling, the box-shadow at the bottom of the navbar changes inste ...

Modify table row background color using PHP based on its position in the table with the use of a function

I am having trouble formatting my table to highlight different rows in distinct colors. The top row should be one color, the second row another, and the bottom two rows a different color each. This is to represent winners, teams getting promoted, and tho ...

Experience the innovative feature of React Splide Carousel where a peek of the next image is shown until you reach

My current challenge arises when I reach the last slide in the slider. I am trying to prevent it from looping and instead stop with no extra space or any other images peeking out. To address this, I have utilized the padding: '5%' option, which ...

When attempting to access the length of a JSON array, it results in undefined

I recently received a JSON encoded array from an AJAX call that looks like this: {"country":{"0":"United States of America","United States of America":{"states":{"0":"Alaska","Alaska":{"cities":["Adak","Akiachak","Akiak","Akutan","Alakanuk"]}}}}} Below ...

Transforming data from a JSON format into a JavaScript array

I'm trying to convert a JSON string into an array containing the values from the JSON. When I use json.stringify(jsonmybe) and alert it, I see [{"role":"noi_user"},{"role":"bert_user"}] (which is in JSON format). My goal is to extract `noi_user` and ` ...

Ways to require semicolons in a Typescript interface

When declaring a TypeScript interface, both , (comma) and ; (semicolon) are considered valid syntax. For example, the following declarations are all valid: export interface IUser { name: string; email: string; id: number; } export interface IUser { ...

What could be causing the side margins on my navbar in mobile view in Bootstrap?

After spending some time working on a simple navbar with CSS styling, I encountered an issue when viewing it in mobile mode. The navbar did not expand to 100% of the screen width and had a margin of about 20px on both sides. CSS .navbar .brand { wi ...

Conceal a row in a table using knockout's style binding functionality

Is it possible to bind the display style of a table row using knockout.js with a viewmodel property? I need to utilize this binding in order to toggle the visibility of the table row based on other properties within my viewmodel. Here is an example of HTM ...

How can the dropdownlist CSS be modified when it is clicked or hovered over?

I recently came across a solution on how to enable a disabled dropdown list when clicked at . I attempted to implement this and added a grey background to the disabled selection. However, I encountered an issue where the background of the dropdown list re ...

Mouseover function ceases to function once an element is dropped

After referencing this discussion, I successfully managed to drag items from one scroll overflow to another. However, the issue arises when these items (or their clones) are in the other scroll overflow as they do not respond to .mouseover(). The goal is ...

Creating a conditional statement within an array.map loop in Next.js

User Interface after Processing After retrieving this dataset const array = [1,2,3,4,5,6,7,8] I need to determine if the index of the array is a multiple of 5. If the loop is on index 0, 5, 10 and so on, it should display this HTML <div class="s ...

Error in GraphQL query: specified argument is mandatory, yet not supplied

I recently started learning about graphql and encountered an issue with my query. Here is the code I am using: { product { id } } "message": "Field "product" argument "id" of type "String!" is requir ...

Emulate sequelize using Jest in combination with sequelize-mock

In my latest project, I have been implementing TDD as the primary methodology along with integration tests. One of the tasks at hand is to retrieve all users from the database. //controller.js const UserService = require('../services/user'); mod ...

Is there a way to access a private table in Google BigQuery using a Python script without needing an authorization token?

Is there a way to submit a query into Google's BigQuery and retrieve results from a python script without needing an authorization code for private tables? The python script is accessed through a user-friendly webpage, so manual authorization code han ...

Best practices for efficiently updating state in React components

Currently, I am in the process of learning React and trying to grasp its concepts by practicing. One exercise I decided to tackle involves deleting an element from an array when a user clicks on it in the UI. Below is the code snippet that I have been work ...

Tips for repairing buttons in the CSS container

The buttons in the CSS search-box are not staying fixed as intended. They should be within the search box, but instead, they are protruding out of the panel. I attempted to utilize z-index, but it did not produce the desired outcome. https://i.sstatic.n ...

As the value steadily grows, it continues to rise without interruption

Even though I thought it was a simple issue, I am still struggling to solve it. What I need is for the output value to increment continuously when I click the button. Here is the code snippet I have been working on: $('.submit').on('click&a ...

Properly defining a DI service in Angular 2.1.2 using ES5

I have created an Angular 2 service that utilizes the Http service and is accessed by other components. However, I am unsure if my implementation is correct: (function (app) { 'use strict'; app.LoaderService = ng.core.Component({ providers: ...

PHP captures the checkbox value through the $_POST method, whereas jQuery removes the checked class from it

I currently have a form with 2 checkboxes: Registered and Not Registered. If the Registered checkbox is ticked, then 2 additional options should appear: Active and Not Active. If the Registered checkbox is unticked, both the Active and Not Active options ...