How to use a VueJS component as a CSS grid items container?

Viewed 305

In my parent component, I have a grid container and a child component:

<template>
  <div>
    <div class="container">
      <grid-items></grid-items>
      <grid-items></grid-items>
      <grid-items></grid-items>
    </div>
  </div>
</template>

The child component contains grid items:

<template>
  <div>
    <div class="item">FOO</div>
    <div class="item">BAR</div>
  </div>
</template>

It doesn't work because I have to surround the grid-items with an extra root div in the child component, breaking the grid logic. If I remove this surrounding div in the child component, I get the following compilation error message:

Component template should contain exactly one root element. If you are using v-if on multiple elements, use v-else-if to chain them instead.

How can I fix this CSS grid logic issue?

2 Answers

You cant, i would do it like this:

<template>
 <div>
   <grid-items></grid-items>
 </div>

And put the container instead in your child component:

<template>
  <div class="container">
    <div class="item">FOO</div>
    <div class="item">BAR</div>
  </div>
</template>

Otherwise you will need to make for every grid item 1 component

I solved it by using vue-fragments plugin thanks to this great article. Below is how I used it.

1. Install the plugin

npm i -s vue-fragment

2. Load it globally in app.js

import Fragment from 'vue-fragment';
Vue.use(Fragment.Plugin);

3. Create parent component grid-container.vue

<template>
  <div class="container">
    <grid-items></grid-items>
    <grid-items></grid-items>
  </div>
</template>

4. Create child component grid-items.vue

<template>
  <fragment>
    <div>FOO</div>
    <div>BAR</div>
  </fragment>
</template>
Related