52

How to generate dynamic class name?

  li v-for='obj in objs'
    | {{ obj.id }} {{ obj.title }}
    div id="obj-{{ obj.id }} " style="float:right; color:red;"

This sample doesn't work! I need this class name to update the div later!!!

NeverBe
  • 5,213
  • 2
  • 25
  • 39

6 Answers6

95

This helped me.

    div :class="['obj-' + obj.id]" style="float:right; color:red;"
NeverBe
  • 5,213
  • 2
  • 25
  • 39
57

I am not familiar with slim-lang, but this is what you need to get inside the Vue template:

<div v-bind:class="['static-class', { 'active-class' : isActive }]">...</div>

In the above case, if isActive evaluates to true, then 'active-class' will be applied. And 'static-class' is always applied in the view. This is called array syntax.

Ref: https://vuejs.org/guide/class-and-style.html#Array-Syntax

You need to ensure that the slim-lang processor emits the above html.

Now, coming to setting an id, you cannot do attribute bindings using moustache ({{...}}) syntax. You need to bind your id as follows:

<div v-bind:id="dynamicId"></div>

Reference: https://vuejs.org/guide/syntax.html#Attributes

Mani
  • 23,635
  • 6
  • 67
  • 54
  • 1
    I'm not sure i understand your examples, i don't need to use conditional classes, i need static ones. – NeverBe Oct 31 '16 at 18:01
29

For multiple classes:

:class="{'form-control':true,['box_'+index]:true}"
Abhinandan
  • 429
  • 8
  • 13
2

In vue ,dynamic classed can be added in several ways.

  • Array
 :class="['prise', index === 0 ? 'first' : '', index === 1 ? 'second' : '']"

here,the prise will be added to the class no matter what happen,but only when the index is equal to 0,then the first will be added to the class name,and index is equal to 1,then the second will be added to the class.

  • Object
  :class= "{ 'ultra-prise','first":index===0,'second':index===1}"

here,in Object case ,the key will be added to the class only when the value is true.

so for this question,simply we can write something like this.

   :class="[`obj-${obj.id}`]"
1

Your code actually work, i guess the problem is vue data setting. I love slim too.

div#posting
  li v-for='obj in objs'
    | {{ obj.id }} {{ obj.title }}
    div id="obj-{{ obj.id }}" class="obj-{{ obj.id }} " style="float:right; color:red;"

javascript:
  var posting;
  posting = new Vue({
    el: '#posting',
    data: {
      objs:
        [
          {id: 1, title: 'xx'},
          {id: 2, title: 'yy'},
        ]
    }
  });

web image show

0
<li v-for="color in colors" :class="[color.style]" class="list">{{color.name}}</li>
</ul>

https://codepen.io/mike-oxhuge/pen/mdOMybP

   data: {
  colors: [
    { id: "1", name: "blue text", style: "blue" },
    { id: "2", name: "red text", style: "red" },
    { id: "3", name: "green text", style: "green" }
  ],
},

Here I made it work. Dynamic name for a class.

Mike K.
  • 637
  • 1
  • 5
  • 18