Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Get Started With Vue Grid in 5 Minutes

DZone 's Guide to

Get Started With Vue Grid in 5 Minutes

In this article, we will quickly implement grid components in Vue with very little coding and configuration.

· Web Dev Zone ·
Free Resource

Vue is the most responsive and progressive framework which is widely used in Single Page Applications. It provides one of the more powerful and flexible ways to display data in a tabular format using the JQWidget Grid component. Grid components are widely used to show smaller/larger sets of data in readable format. You can show read-only views or editable views.

Nested grid feature in vue grid

In this article, we will quickly implement JQwidget grid components in Vue with very little coding and configuration.

Integration

We need Node.js v. 8 to install the Vue CLI. Check the node version by using the node –v, or you can upgrade version with npm install npm@latest –g. 

CLI stands for command line interface and Vue CLI provides a full rapid Vue.js development. It allows us to select which libraries our project will be using, helps in configuring Webpack, and allows us to write HTML, CSS, and JavaScript. We can use single-file .vue components, TypeScript, SCSS, Pug, the latest versions of ECMAScript, etc. It enables Hot Module Replacement when you save your project; changes appear instantly in the browser. This configuration is based on webpack-dev-server

To install CLI, run: 

npm i -g @vue/cli

To create a Vue project using CLI, type the below command in the Vue CLI:

Vue create DataGrid-Vue

This will start the creation of the project, which will then present an option to pick a default preset or manually select features. Select the features for the project manually. Once our project is created run,

npm run serve 

Our project will run at localhost:8080.

Folder Structure of a Vue Project

Once the project is created below is the project structure.

Image title

You can get the configuration of the package.json file from the source code below. All the needed modules are included.

{  
  "name": "vue",  
  "version": "0.1.0",  
  "private": true,  
  "scripts": {    
    "start": "vue-cli-service serve",    
    "build": "vue-cli-service build",    
     "lint": "vue-cli-service lint"  
  },  
  {
  "dependencies": {
    "jqwidgets-scripts": "~6.1.0",
    "vue": "^2.5.16"
  },
  "devDependencies": {    
    "@vue/cli-plugin-babel": "^3.0.0-beta.9",    
    "@vue/cli-plugin-eslint": "^3.0.0-beta.9",    
    "@vue/cli-service": "^3.0.0-beta.9",    
    "vue-template-compiler": "^2.5.13"  
    },  
    "babel": {    
    "presets": [ "@vue/app"    ]  },  
    "eslintConfig": {    
    "root": true,    
    "extends": [      
    "plugin:vue/essential",      
    "eslint:recommended" ]  
    },  
    "postcss": { 
    "plugins": { "autoprefixer": {} }  
    },  
    "browserslist": ["> 1%", "last 2 versions", "not ie <= 8" ]
    }

After the package.json is ready, type  npm install in your CLI.

Creating an Application Using Grid

Navigate to the public folder and create the index.html file. It should be a simple HTML document with one <div/> where the data will be rendered using a straightforward template syntax.

Index.Html

<!DOCTYPE html>
<html>
    <head>
        <title id='Description'>Demo Of View Grid Functionality</title>
        <meta name="description" content="Demo of View Grid." />
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">

    <link rel="stylesheet" href="../jqwidgets/styles/jqx.base.css" type="text/css" />
    <script type="text/javascript" src="../scripts/demos.js"></script>
    </head>
    <!-- Display the application -->
    <body>
        <div class="example-description">
            Demo of Basic Functionality of Grid .
        </div>
        <div id="app"></div>
        <script src="../dist/grid_defaultfunctionality.bundle.js"></script>
    </body>
</html>

The next step is to navigate to the src folder. In this folder, you will create the main.js file. You will have to add a simple configuration there.

Main.js

import Vue from 'vue'
import App from './App.vue'
Vue.config.productionTip = false
new Vue({  
  render: h => h(App)
}).$mount('#app')

In the same folder, you have to create the App.vue file, which is the main file for your application.

App.vue

In the same folder, you have to create the App.vue file, which is the main file for your application. It has three sections: template, scripts, and style. Below is the format for App.vue for the Grid component. The App.vue has a <template/> structural tag where the application structure is determined. You have to set the tags for the new components <JqxGrid/> there.

<template>
  <JqxGrid
    ref="grid"
    :width="width"
    :source="dataAdapter"
    :columns="columns"
    :columnsresize="true"
    :pageable="true"
  ></JqxGrid>
</template>
<script>
import JqxGrid from "jqwidgets-scripts/jqwidgets-vue/vue_jqxgrid.vue";

export default {
  components: {
    JqxGrid
  },
  data: function() {
    return {
      width: 900,
      dataAdapter: new jqx.dataAdapter(this.source),
      columns: [
        { text: "Name", datafield: "name", width: 200 },
        { text: "Last Name", datafield: "lname", width: 200 },
        { text: "Product", datafield: "product", width: 150 },
        { text: "Quantity", datafield: "quantity", width: 150, cellsalign: 'right' },
        { text: "Unit Price", datafield: "price", minwidth: 100, cellsalign: 'right', cellsformat: 'c2' }
   { text: "Total", datafield: "total", cellsalign: 'right', cellsformat: 'c2'}
      ]
    };
  },
  beforeCreate: function() {
    // Add here any data where you want to transform before components be rendered
    this.source = {
      datatype: "json",
      datafields: [
        { name: 'firstname', type: 'string' },
        { name: 'lastname', type: 'string' },
        { name: 'productname', type: 'string' },
        { name: 'quantity', type: 'number' },
        { name: 'price', type: 'number' },
        { name: 'total', type: 'number' } 
      ],
      /// for hardcoded data use localdata:
      ///url for your data Eg:
      url: "GetData/ItemsList.txt"
    };
  }
};
</script>

<style>
</style>

In the <script/> section, import Grids from JQWidgets .

import JqxGrid from "jqwidgets-scripts/jqwidgets-vue/vue_jqxgrid.vue"; 

In components, add  JqxGrid  to Vue class,

components: {JqxGrid}, 

Properties of a Grid

The properties of the <JqxGrid/> component are defined in the data member of the Vue class. You should put them in the return object of the data function:

data: function() {
    return {
      width: 900,
      dataAdapter: new jqx.dataAdapter(this.source),
      columns: [
        { text: "Name", datafield: "name", width: 200 },
        { text: "Last Name", datafield: "lname", width: 200 },
        { text: "Product", datafield: "product", width: 150 },
        { text: "Quantity", datafield: "quantity", width: 150, cellsalign: 'right' },
        { text: "Unit Price", datafield: "price", minwidth: 100, cellsalign: 'right', cellsformat: 'c2' }
        { text: "Total", datafield: "total", cellsalign: 'right', cellsformat: 'c2'}
      ]
    };
  },

Set Data Dynamically

Web pages load data dynamically using a REST framework or Web APIs. To load data dynamically we need to add url: field in a return sttement. Also set the datatype.

url: "GetData/ItemsList.txt"datatype: "JSON" 

Below is the basic grid for vue framework.

Grid component

Enabling Features of Grid Components

Sorting, Filtering, Grouping, paging, editing, drag-and-drop, and nested grids are some of the enabling features of the grid. Before we look into how to enable these features for better user experience, we need to add bundle.js files for respective features in index.html, e.g., adding bundle files for sorting in the index.htm file.

<div id="app"></div>
<script src="../dist/grid_sorting.bundle.js"></script>

Sorting

The sortable property enables or disables the data sorting. In the code example below, the grid's data sorting is enabled:

<JqxGrid :width="width" :source="dataAdapter" :columns="columns"
         :sorting="true">
</JqxGrid>

To enable or disable the sorting of a grid column, you can set its sortable property to false. Also, when the sorting data type is Date, Number or Boolean, the 'type' property in the 'datafield' array should be set.

The sortcolumn property specifies the default grid sort column, i.e. when the grid is displayed, the data will be sorted. The sortdirection property specifies the sort order of the sort column.

sortcolumn: 'ColumnName',sortdirection: 'asc' 

The sortby function can be used to sort the grid through the API. This function should be called when the grid data is fully loaded. The first parameter is the Column's DataField. The second parameter is the sort order - 'asc' or 'desc'.

mounted: function () {
this.$refs.myGrid.sortby('FirstName', 'asc');
} 

To remove the sorting, call the removesort function. When the data is sorted, the Grid raises the sort event.

<JqxGrid ref="myGrid" @sort="onSort($event)"
         :width="width" :source="source" :columns="columns">
</JqxGrid>

Image title

Filtering

To enable the filtering feature, you need to set the 'filterable' property to true. When the value of the filterable property is true, the Grid displays a filtering panel in the columns' popup menus. There are methods “addfilter”, “removefilter” , “applyfilters”, “clearfilter” to customize filtering in the grid .

<JqxGrid :width="width" :source="dataAdapter" :columns="columns"
:sorting="true"  :filterable="true" : :autoshowfiltericon="true" :ready="ready">
</JqxGrid>

Image title

Grid Grouping

The jqxGrid component supports data grouping against one or more columns. Grouping is allowed if the 'groupable' property is set to true. End-users can group data by dragging column headers to the Group Panel. This panel's visibility is controlled by the showgroupsheader property.

The code example below shows a Grid template with one grouping column:

<JqxGrid ref="myGrid" :width="width" :source="dataAdapter" :columns="columns" :groupable="true" :groups="[City]">
</JqxGrid>

Image title

Grid Paging

The jqxGrid component has a built-in paging capability that supports paging functionality. The paging functionality is enabled when the 'pageable' property is set to true. The code example below illustrates how to enable the paging functionality.

<JqxGrid @pagechanged="onPageChanged($event)" @pagesizechanged="onPageSizeChanged($event)"
         :width="width" :source="source" :columns="columns" 
         :pageable="true">
</JqxGrid>

When a page is changed or the page size is changed, the Grid raises the pagechanged or pagesizechanged events.

methods: {
    onPageChanged: function(event) {
        let args = event.args;
        let pagenumber = args.pagenum;
        let pagesize = args.pagesize;
    },
    onPageSizeChanged: function (event) {
       let args = event.args;
       let pagenumber = args.pagenum;
       let pagesize = args.pagesize; 
    }
}

The Grid Page Size options are displayed in a DropDownList component in the pager area. By default, the size options are 5, 10, and 20. The pagesizeoptions property enables you to set new size options.

<JqxGrid :width="width" :source="source" :columns="columns"
         :pageable="true" :pagesizeoptions="['10', '20', '30']">
</JqxGrid>

The pagesize property sets the default page size when the paging functionality is enabled. By default, the Grid displays 10 rows in a page. The pagerrenderer property allows you to customize the UI of the Grid pager.

Image title

Grid Cell Editing

The jqxGrid Cell Editing feature resembles the data entering experience in an Excel Spreadsheet – once you select a grid cell, you can enter data when you start typing text. The Grid's editable property specifies whether the editing is enabled or not.

The Grid has APIs for showing and hiding the cell editors. The begincelledit method allows you to put a specific cell into edit mode.

this.$refs.myGrid.begincelledit(0, Quantity); 

The endcelledit method ends the edit operation and confirms or cancels the changes.

The following code cancels the changes:

this.$refs.myGrid.endcelledit(0, Quantity, true); 

The following code cancels the changes:

this.$refs.myGrid.endcelledit(0, Quantity, false); 

To set a new value to a Grid cell, you can use the setcellvalue method:

// the first parameter is the row's index.
// the second parameter is the column's datafield.
// the third parameter is the new cell's value.
this.$refs.myGrid.setcellvalue(0, ‘Quantity’, 'My Value');

To get the value of a Grid cell, you can use the 'getcellvalue' method: 

// the first parameter is the row's index.
// the second parameter is the column's datafield.
let value = this.$refs.myGrid.getcellvalue(0, 'lastname');

The 'cellbeginedit' and 'cellendedit' events are raised when the edit operation begins or ends. 

<JqxGrid @cellbeginedit="onCellBeginEdit($event)" @cellendedit="onCellEndEdit($event)"
         :width="width" :source="dataAdapter" :columns="columns"
         :editable="true">
</JqxGrid>

...
methods: {
    onCellBeginEdit: function (event) {
        let args = event.args;
        let columnDataField = args.datafield;
        let rowIndex = args.rowindex;
        let cellValue = args.value;
    },
    onCellEndEdit: function (event) {
        let args = event.args;
        let columnDataField = args.datafield;
        let rowIndex = args.rowindex;
        let cellValue = args.value;
        let oldValue = args.oldvalue;
    }
}

The Grid will display a validation popup message when the new cell's value is not valid. The developers are able to set a custom validation logic and error messages for each grid column. The Grid will stay in edit mode until a correct value is entered or the user presses the "Esc" key.

Image title


These examples demonstrate how to use jqGrid and also how to enable its features. I hope you can use these examples for your guidance to use jqGrid in an SPA.

Topics:
javascript ,vue.js tutorial ,web dev ,javascript components ,vue.js components

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}