Search code examples
vue.jsnativescriptnativescript-vue

How to dynamically arrange items in a GridLayout?


I am printing some labels by looping through an array in Nativescript-Vue. I want the labels to arranged in a Grid. This is my template:

<GridLayout columns="auto,auto" rows="auto,auto">
  <label
    v-for="(item, index) in items"
    :text="item"
    :key="index"
  />
</GridLayout>

and this is the items array:

export default {
  data() {
    return {
      items: ["A", "B","C","D","E","F"]
    }
  }

How do I dynamically assign the row and column attribute to <label> ? I can do it manually but won't be able to loop through the array then. I want it to be in order, like

A | B

C | D

E | F


Solution

  • Use computed property to calculate the number of rows based on number of items. Then bind the row & col for each Label based on index.

    <template>
        <Page class="page">
            <ActionBar title="Home" class="action-bar" />
            <ScrollView>
                <GridLayout columns="*,*" :rows="rows">
                    <Label v-for="(item, index) in items" :text="item" :key="index"
                        :row="index / 2" :col="index % 2" class="h1"></Label>
                </GridLayout>
            </ScrollView>
        </Page>
    </template>
    
    <script>
        export default {
            data() {
                return {
                    items: ["A", "B", "C", "D", "E", "F"]
                };
            },
            computed: {
                rows: function() {
                    const rows = [];
                    for (let i = 0; i < this.items.length / 2; i++) {
                        rows.push("auto");
                    }
                    return rows.join(",");
                }
            }
        };
    </script>
    

    Playground Sample