A. L
A. L

Reputation: 12639

Auto create second row if element length exceeds certain value

So I'm trying to make it so that if there's greater than six elements, it will have half of the elements in the top and the other half on the bottom.

Currently I'm doing it like this (in Vue.js):

<table>
    <tbody>
        <template v-if="cards.length <= 6">
            <tr>
                <td v-for="card in cards">
                    {{ card }}
                </td>
            </tr>
        </template>
        <template v-else>
            <tr>
                <td v-for="card in cardsFirstHalf">
                    {{ card }}
                </td>
            </tr>
            <tr>
                <td v-for="card in cardsSecondHalf">
                    {{ card }}
                </td>
            </tr>
        </template>
    </tbody>
</table>

Is there a better way to do this?

Upvotes: 0

Views: 49

Answers (1)

Eric Guan
Eric Guan

Reputation: 15992

It's easier to implement your requirements thru js

https://jsfiddle.net/qapf3yfL/1/

HTML:

<div id="app">
<table>
    <tbody>
            <tr v-for="row in rows">
                <td v-for="card in row">
                    {{ card }}
                </td>
            </tr>
    </tbody>
</table>
</div>

JS:

new Vue({
    el: '#app',
    data: {
        max: 6,
        cards: ['c1', 'c2', 'c3', 'c4', 'c5', 'c6', 'c7']
    },
    computed: {
        rows() {
            let cards = this.cards;
            if (cards.length <= this.max)
                return [cards]

            var mid = Math.ceil(cards.length / 2);
            return [cards.slice(0, mid), cards.slice(mid)]
        }
    }

})

Upvotes: 1

Related Questions