Insert v-for data into css class in Vuejs2

Asked

Viewed 135 times

0

<template v-for="d in data" >
     <a :key="d.id" class="zone{{d.value}}" href="{{d.code}}" >{{d.name}}</a>
</template>

This example just doesn’t work, how can I pass the values then within "d" to the attributes? How do I resolve this impasse?

1 answer

0


I didn’t quite understand the doubt, but I think the problem is in the way you’re using the interpolation.

The interpolation "{{}}" is used only between the tags, and not within them, referencing their variables that are within computed or his data ().

In case, in a tag inside an attribute nay interpolation is used, rather than v-bind: or the two points ":", which is exactly equal to v-bind, but in a shorter form to use it.

Your code in case I think would look like this:

<template v-for="d in data" >
     <a :key="d.id" class="zone" :class="d.value" :href="d.code" >{{ d.name }}</a>
</template>

I just don’t quite understand what you wanted to do exactly in the case of the attribute class, so I assumed the class zone is static, and the d.value shall be another dynamic class, against the value of the variable.

In this case it has no problem of having two class attributes in a tag, Vuejs will perform a merge of all classes automatically, of the dynamics with the static ones.

  • 1

    That was exactly my question, my mistake was that I wasn’t using v-bind. As for class, was supposed to be like class="zone1" but I saw that it can also be used like this :class="'zone'+d. value". liked the hint of grouping classes, this will be very useful.

  • One other thing I just noticed, the :key that you’re putting on the tag <a> is probably incorrect. It is to be used in the same tag as v-for. In this case, as the v-for is a template you won’t be able to use, so you can even remove from the tag <a>, but if it were in a <div> for example, it is advisable to even, but then you put on own <div> who is performing the v-for.

  • In fact, this :key is only there by requirement of vuejs2 itself. Eslint-plugin-Vue complains that it is now recommended to use v-bind:key when making v-for loops, but if I remove it, the code works the same way.

  • So, what I was trying to say is that it does, only it has to be in the same tag as the v-for, and not the ones inside it.. but ok.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.