Home > Mobile >  Vue 2 - Styling HTML returned in a switch statement
Vue 2 - Styling HTML returned in a switch statement

Time:02-08

I'm building a generic component supposed to receive various backend data. I wrote a switch. One condition is :

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

I use v-html in my template, therefore in this case, we have 3 divs created, each with a class of "base" and then "b1", "b2", "b3". I can see on the webpage that these classes are properly set when I inspect the elements.

I've described in my style some rules for theses classes (mostly background-color, border-radius and so on), but they do not apply.

I'm guessing this might have something to do with the CSS being applied before these divs are created but I'm not sure of this.

What should I do to get these tags created by JS to be styled properly ?

(Also, I know using v-html can be dangerous, therefore if you have a better idea for this whole thing, I'm all ears)

CodePudding user response:

There is no need to build the markup in component methods. Define it in template and bind the classes dynamically. Since you didn't post the api data structure, neither how you are using this snippet of code, I can only refactor the specific case.

<div 
  v-for="base in colValues" 
  :>
  {{base.name}}
</div>

CodePudding user response:

Figured it out. For those wondering, switch statements returning html code aren't styled if the tag in your file is scoped. Unsure why, but removing scoped work. If you decide to do so, but unique class names, as these styles will spread all throughout the application !

  •  Tags:  
  • Related