Stylizing HTML generated from a switch statement in Vue 2

I am currently working on a versatile component that is designed to receive different types of backend data. Within my code, I have implemented a switch statement with one condition being:

case 'Bases':
                let bases = variant[tableName][colValue].map((base) => {
                    return `<div class="base b${base.strongestIndication}">${base.name}</div>`
                })
                return bases.join('')

My template utilizes v-html, which results in the creation of 3 divs each with classes "base", "b1", "b2", and "b3". These classes are correctly applied when inspecting the elements on the website.

In the CSS styles, I have specified rules for these classes (such as background-color, border-radius, etc.), but they do not seem to be taking effect.

I suspect that this issue may be related to the fact that the CSS is being applied before the divs are created programmatically, but I am uncertain.

How can I ensure that these dynamically created tags are styled properly using JavaScript?

(Additionally, I acknowledge the potential risks associated with using v-html, so if you have alternative suggestions for this implementation, I am open to hearing them)

Answer №1

Instead of constructing the markup within component methods, it is recommended to define it in the template and bind the classes dynamically. Without knowing the data structure from the API or how this code snippet is being utilized, I can only optimize for the specific scenario at hand.

<div 
  v-for="base in colValues" 
  :class="['base', `b${base.strongestIndication}`]">
  {{base.name}}
</div>

Answer №2

Managed to solve the issue. Just a heads up for anyone curious, switch statements that return HTML code may not be styled properly if the style tag in your file is scoped. I'm not exactly sure why, but removing the scoped attribute seems to fix it. If you choose to remove it, make sure to use unique class names to prevent these styles from affecting other parts of the application!

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

Despite including the necessary statements, AngularJS is still generating "Missing 'use strict' statement" errors

I encountered an issue when using Grunt's Jshint-Task with my controller and two modules split into three files. Despite including the "use strict" statement in all three files, I still receive an error prompting me to add it. As a newcomer to Angular ...

Shifting the key of a choropleth map with R, rMaps, and datamaps

My challenge is to center the legend below a choropleth map of the United States. I don't have much experience with JS or CSS, but I decided to delve into the datamaps.all.min.js file in the R-3.2.1\library\rMaps\libraries\datamaps ...

Utilizing the POST route as a middleware: a step-by-step guide

I am working on 2 different routes users.js POST api/users auth.js POST api/auth/confirmation My goal is to utilize the auth/confirmation as middleware in the /users route Initially, I attempted to create a temporary function and use res.redirect(... ...

Combine two objects while keeping only specific properties

Currently facing a challenge with merging two objects in the desired way using Node.js express and MongoDB. Here are the initial objects: Obj1: { "name":"max", "age":26, "hometown": & ...

Need to invoke a controller method multiple times? Utilize AJAX for seamless and efficient execution

Apologies if this question seems simple, but I'm struggling to find a solution. I've implemented a straightforward method in a controller: public string ExactSeconds() { string str = DateTime.Now.Second.ToString(); return str; ...

What would be the optimal method for adding a label property to every object within an array nested inside an object?

Issue Overview: I am facing a challenge in adding labels to values inside an array property of an object. The data consists of different Insights retrieved from Facebook's Graph API. We are gathering information on 25 various metrics... My focus ...

Node - What could be causing my gif to run at a slower pace while utilizing GifEncoder?

I am encountering an issue with rendering a Gif using the GifEncoder library (specifically, an older version). The output gif is much slower and appears to lag. Below is the code I have been using: import GIFEncoder from "gif-encoder-2"; import f ...

What is the best way to eliminate the input border?

click here for image I'm currently working on designing a straightforward login page. However, I've noticed that there are black borders around the input fields. Can anyone help with how to remove these borders? ...

What is the precise mechanism behind the functioning of rails respond_to feature?

Currently, I'm in the process of developing an application that requires a remote form feature. As I work on this, I've realized that I have never fully grasped how Rails' respond_to function operates. Let's consider the code snippet b ...

How to position two divs in a row using Bootstrap

Looking at the output below: https://i.stack.imgur.com/pQM8F.png The blue circle is placed in one div, while the text is in another. I'm perplexed by why the first div appears on top and the second doesn't seem to align properly. Here's th ...

Dynamic stylesheet in Vue component

Currently, I am utilizing a Vue component (cli .vue) and facing the challenge of selectively displaying my stylesheet based on a boolean value. To put it simply: When myVar==false, the component should not load its styles. <style v-if="myVar" lang="sc ...

Using jquery to rotate images

I have a collection of images that I would like to display one by one with a 3D and 2D rotation effect. The HTML structure is as follows: <div><img src="1.jpg"></div> <div><img src="2.jpg"></div> <div><img src ...

Retrieving JSON data

Here is a URL that returns JSON data: Link. I am attempting to access this data with the following script: $.ajax({ type: 'GET', url: 'http://www.spritpreisrechner.at/espritmap-app/GasStationServlet?data=%5B%22Stgilgen%22%2C%22DIE%22%2C13 ...

Issues with CSS causing items to not line up in a single row

I'm currently working on an html/css page and trying to align the items of the agenda class in the same row, centered on the page. https://i.sstatic.net/8TjG8.png Here's the code I've been using: <html lang="en" xmlns="ht ...

Troubleshooting a CSS problem with iPad browsers

I have a specific issue related to CSS on iPad. I am working with a set of sublinks and have defined the styles in CSS as follows: #leftNav .searchBySub {...} #leftNav a.searchBySub:hover {...} #leftNav .searchBySubClicked {...} In my JavaScr ...

"Learn the process of customizing the border color of a drop-down menu using

Is there a way to add validation to a drop-down menu so that the border color turns red if an option is not selected? $("#MainContent_ddlSuppliers option:selected'").css("border", "1px solid #F78181"); ...

Sending JSON data two times to the ASP.NET MVC controller via POST request

function onTestComplete(content) { var url = '<%= Url.Action("JsonTest","Organization") %>'; $.post(url, null, function(data) { alert(data["name"]); alert(data["ee"]); }); } <% using (Ajax.BeginForm("JsonTe ...

Encountering ESLint error in WebStorm: Parsing issues with imported module

These are the imports causing the issue: import { HttpClient } from '@angular/common/http'; import { ConfirmationService, MessageService } from "primeng/api"; The error message I encountered is ESLint: Parse errors in imported module '@an ...

Rotating objects with the keyboard in Three.js

Searching for assistance to rotate a 3D object along the y-axis with a keyboard input (B). Anyone available to help? I've been struggling with this issue for days now, every attempt at coding leads to errors. Please, any help would be greatly apprec ...

Determine the size of an array by utilizing the map function in ES6

Attempting to determine the length of an array using ES6 with the following code, but encountering issues. a=[[1,2,3,4],[4,5,6]] result = a.map(d=>({d[0]:d.length})) console.log(result) The correct method is: a=[[1,2,3,4],[4,5,6]] result = a.map(d=&g ...