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!!!
This helped me.
div :class="['obj-' + obj.id]" style="float:right; color:red;"
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>
In vue ,dynamic classed can be added in several ways.
: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.
: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}`]"
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'},
]
}
});
<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.