1

The CSS grid layout described here shows that the cells of the grid are added to the markup without any hierarchy, and the layouting into rows and columns is controlled by the CSS directives (grid-template-columns for instance).

An example for creating a 4 columns x 2 rows grid would be:

<div style='display: grid; grid-template-columns: 1fr 1fr 1fr 1fr;'>
  <div>1</div>
  <div>2</div>
  <div>3</div>
  <div>4</div>
  <div>5</div>
  <div>6</div>
  <div>7</div>
  <div>8</div>
</div>

I'm having difficulty using this concept together with a template language, where an iterator is iterating over records, and each iteration creates a row container with the individual elements. The grid lays out the row container instead of its children.

Using a Vue template as an example, the above could be dynamically rendered as follows:

<div style='display: grid; grid-template-columns: 1fr 1fr 1fr 1fr;'>
  <div v-for='item in items>
    <div>{{item.a}}</div>
    <div>{{item.b}}</div>
    <div>{{item.c}}</div>
    <div>{{item.d}}</div>
  </div>
</div>

...but this will render a 4 blocks of each item in a row (I'd like the item.a ... item.d to make up the row elements, and each item to represent a row).

How would one be able to achieve this? or is this generally not possible with a template language?

1 Answer 1

2

To avoid creating a container element per iteration, use a <template> with v-for (instead of <div>):

new Vue({
  el: '#app',
  data() {
    return {
      items: [
        { a: 1, b: 2, c: 3, d: 4 },
        { a: 2, b: 3, c: 4, d: 5 },
        { a: 3, b: 4, c: 5, d: 6 },
        { a: 4, b: 5, c: 6, d: 7 },
      ]
    }
  }
})
<script src="https://unpkg.com/[email protected]/dist/vue.min.js"></script>

<div id="app">
  <div style='display: grid; grid-template-columns: 1fr 1fr 1fr 1fr;'>
    <template v-for='item in items'>
      <div>{{item.a}}</div>
      <div>{{item.b}}</div>
      <div>{{item.c}}</div>
      <div>{{item.d}}</div>
    </template>
  </div>
</div>

Sign up to request clarification or add additional context in comments.

2 Comments

Interesting - I didn't know that you could use <template> also for that purpose. Do you have a link to the docs or is that an undocumented "feature"?
@orange Added link to answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.