Menu Close

Build a Drag and Drop Grid with Vuejs

We can create a draggable and sortable grid with the vue-js-grid package.

It’s easy to use.

First, we install it by running:

npm install vue-js-grid

Next, we can use it by writing:

main.js

import Vue from "vue";
import App from "./App.vue";
import Grid from "vue-js-grid";

Vue.use(Grid);

Vue.config.productionTip = false;

new Vue({
  render: h => h(App)
}).$mount("#app");

We registered the Grid component from vue-js-grid globally with Vue.use.

App.vue

<template>
  <div id="app">
    <grid :draggable="true" :sortable="true" :items="items" :height="100" :width="100">
      <template slot="cell" scope="props">
        <div>{{props.item}}</div>
      </template>
    </grid>
  </div>
</template>

<script>
export default {
  name: "App",

  data() {
    return {
      items: Array(50)
        .fill()
        .map((_, i) => i)
    };
  }
};
</script>

We created an array with 50 minutes as the property of items.

To do that we created an array with 50 elements with Array(50).

Then we called fill and map to fill the entries with numbers.

In the template, we have the grid component with a few props.

draggable is set to true to make the grid items draggable.

sortable is also set to true so that we can sort then entries.

items is set to items. This is the prop for setting the grid items.

height sets the height of the grid in percentage.

width sets the width as a percentage.

In the grid component, we have the template to render to grid items.

Now we get a responsive grid with 50 numbers displayed as the content.

It responds to resizing so it’s responsive.

We can drag and drop them grid items as we wish.

This is one of the easiest components for creating a drag and drop grid.

Posted in vue