I am very new to vue, and still stuck with some conditional that I usually solved with PHP. I am trying to loop an element with a conditional inside it. Here is the element i want to look like:
<ul>
<li>A</li>
<li>B</li>
</ul>
<ul>
<li>C</li>
<li>D</li>
</ul>
Here is my code :
<template v-for="(grade , counter) in grades">
<template v-if="counter % 2 === 0">
<ul>
</template>
<li>{{ grade }}</li>
<template v-if="counter % 2 == 1">
</ul>
</template>
</template>
<script>
new Vue({
el : "#app",
data : {
grades : ['A', 'B', 'C', 'D'],
},
});
</script>
And the result is :
<ul>
</ul>
<li>A</li>
<li>B</li>
<ul>
</ul>
<li>C</li>
<li>D</li>
Sorry the above code is just an example, but more or less it is the problem i am dealing with. Can someone help me with this? Thank you.
I recommend using the render
function in this case to reduce the complexity in the template as below
new Vue({
el: "#app",
data: {
grades: ['A', 'B', 'C', 'D'],
},
render (createElement) {
const elements = [];
const step = 2;
for (let i = 0; i < this.grades.length; i += step) {
elements.push(
createElement(
'ul',
{},
this.grades.slice(i, i + step).map(grade => createElement('li', {}, grade)))
)
}
return createElement('div', {}, elements);
}
});
JSFiddle: https://jsfiddle.net/cf37vta9/