Framework:Javascript GridAngular GridReact GridVue Grid

Vue Grid: Get Started with AG Grid

AG Grid is the industry standard for Vue Enterprise Applications. Developers using AG Grid are building applications that would not be possible if AG Grid did not exist.

Quick Look Code Example
import "ag-grid-community/dist/styles/ag-grid.css";
import "ag-grid-community/dist/styles/ag-theme-alpine.css";
import { AgGridVue } from 'ag-grid-vue';

export const App = {
    name: 'App',
    data() {
        return {
            columnDefs: null,
            rowData: null
        }
    },
    components: {
        AgGridVue
    },
    beforeMount() {
        this.columnDefs = [
            { field: 'make' },
            { field: 'model' },
            { field: 'price' }
        ];

        this.rowData = [
            { make: 'Toyota', model: 'Celica', price: 35000 },
            { make: 'Ford', model: 'Mondeo', price: 32000 },
            { make: 'Porsche', model: 'Boxter', price: 72000 }
        ];
    },
    template: `
        <ag-grid-vue
            style="width: 500px; height: 300px;"
            class="ag-theme-alpine"
            :columnDefs="columnDefs"
            :rowData="rowData">
        </ag-grid-vue>
    `
}
import Vue from 'vue';
import { App } from './app';

new Vue({
  el: '#root',
  render: h => h(App)
});

In this article, we will walk you through the necessary steps to add AG Grid (both Community and Enterprise are covered) to an existing Vue project, configure some of the essential features of it. We will show you some of the fundamentals of the grid (passing properties, using the API, etc). As a bonus, we will also tweak the grid's visual appearance using Sass variables.



We offer two versions of Vue support - one for Vue 2 and one for Vue 3. The only difference in use is how you import the dependency:

VersionPackage ImportsModule Imports
Vue 2@ag-grid-community/vueag-grid-vue
Vue 3@ag-grid-community/vue3ag-grid-vue3

If you unsure what import type to use you should use the package import type (i.e. ag-grid-vue/ ag-grid-vue3).

For more information on import types please refer to the documentation here.

This tutorial, as well as ll of our examples, use Vue 2 by default.

For the Vue 3 version of this tutorial please see the documentaiton here.

Add AG Grid to Your Project

For the purposes of this tutorial, we are going to scaffold an Vue app with Vue CLI. Don't worry if your project has a different configuration. Ag-Grid and its Vue wrapper are distributed as NPM packages, which should work with any common Vue project module bundler setup. Let's follow the Vue CLI instructions - run the following in your terminal:

npm install -g @vue/cli
vue create my-project

When prompted choose "Manually select features":

Vue CLI v4.5.12
? Please pick a preset:
  Default ([Vue 2] babel, eslint)
  Default (Vue 3 Preview) ([Vue 3] babel, eslint)
❯ Manually select features

Next, select Babel and CSS Pre-processors (we've also deselected Linter here, but this is optional):

Vue CLI v4.5.12
? Please pick a preset: Manually select features
? Check the features needed for your project:
  ◉ Choose Vue version
  ◉ Babel
  ◯ TypeScript
  ◯ Progressive Web App (PWA) Support
  ◯ Router
  ◯ Vuex
❯ ◉ CSS Pre-processors
  ◯ Linter / Formatter
  ◯ Unit Testing
  ◯ E2E Testing

Select version 2.x when prompted:

Vue CLI v4.5.12
? Please pick a preset: Manually select features
? Check the features needed for your project: Choose Vue version, Babel, CSS Pre-processors
? Choose a version of Vue.js that you want to start the project with (Use arrow keys)2.x
  3.x (Preview)

Next select Sass/SCSS (with node-sass) as the CSS Pre-processor:

Vue CLI v4.5.12
? Please pick a preset: Manually select features
? Check the features needed for your project: Choose Vue version, Babel, CSS Pre-processors
? Choose a version of Vue.js that you want to start the project with 2.x
? Pick a CSS pre-processor (PostCSS, Autoprefixer and CSS Modules are supported by default):
  Sass/SCSS (with dart-sass)
❯ Sass/SCSS (with node-sass)
  Less
  Stylus

Now choose where to store the configuration data - we've opted for dedicated config files:

Vue CLI v4.5.12
? Please pick a preset: Manually select features
? Check the features needed for your project: Choose Vue version, Babel, CSS Pre-processors
? Choose a version of Vue.js that you want to start the project with 2.x
? Pick a CSS pre-processor (PostCSS, Autoprefixer and CSS Modules are supported by default): Sass/SCSS (with node-sass)
? Where do you prefer placing config for Babel, ESLint, etc.? (Use arrow keys)
❯ In dedicated config files
  In package.json

Finally you can choose to save this configuration for all future projects - what you choose here will depend on your development setup & standards, so for the purposes of this tutorial we'll select No:

Vue CLI v4.5.12
? Please pick a preset: Manually select features
? Check the features needed for your project: Choose Vue version, Babel, CSS Pre-processors
? Choose a version of Vue.js that you want to start the project with 2.x
? Pick a CSS pre-processor (PostCSS, Autoprefixer and CSS Modules are supported by default): Sass/SCSS (with node-sass)
? Where do you prefer placing config for Babel, ESLint, etc.? In dedicated config files
? Save this as a preset for future projects? (y/N) N

After a few seconds the newly created my-project will be ready - let's start our application:

cd my-project
npm run serve

If everything goes well, npm run serve has started the web server. You can open the default app at localhost:8080.

Next let's add the AG Grid NPM packages. Run the following command in my-project:

npm install --save ag-grid-community ag-grid-vue vue-property-decorator@^8.0.0

After a few seconds of waiting, you should be good to go. Let's get to the actual coding! As a first step, let's add the AG Grid styles - replace the style block in src/App.vue with the follow:

<style lang="scss">
  @import "../node_modules/ag-grid-community/dist/styles/ag-grid.css";
  @import "../node_modules/ag-grid-community/dist/styles/ag-theme-alpine.css";
</style>

The code above imports the grid "structure" stylesheet (ag-grid.css), and one of the available grid themes: (ag-theme-alpine.css). AG Grid ships several different themes - pick one that matches your project design.

In a later section we documentation on how you can Customise the Theme Look using SCSS, which is our recommended approach.

As this will be a simple example we can delete the src/components directory - our example application will live in src/App.vue.

Let's add the component definition to our template. Edit app/App.vue and replace the scaffold code:

<template>
    <ag-grid-vue style="width: 500px; height: 500px;"
        class="ag-theme-alpine"
        :columnDefs="columnDefs"
        :rowData="rowData">
    </ag-grid-vue>
</template>

This is the ag-grid component definition, with two property bindings - rowData and columnDefs. The component also accepts the standard DOM style and class. We have set the class to ag-theme-alpine, which defines the grid theme. As you may have already noticed, the CSS class matches the name of CSS file we imported earlier.

Now let's replace the script section ofsrc/App.vue:

<script>
    import { AgGridVue } from "ag-grid-vue";

    export default {
        name: 'App',
        data() {
            return {
                columnDefs: null,
                rowData: null
            }
        },
        components: {
            AgGridVue
        },
        beforeMount() {
            this.columnDefs = [
                { field: 'make' },
                { field: 'model' },
                { field: 'price' }
            ];

            this.rowData = [
                { make: 'Toyota', model: 'Celica', price: 35000 },
                { make: 'Ford', model: 'Mondeo', price: 32000 },
                { make: 'Porsche', model: 'Boxter', price: 72000 }
            ];
        }
    }
</script>

<style lang="scss">
   @import "../node_modules/ag-grid-community/dist/styles/ag-grid.css";
   @import "../node_modules/ag-grid-community/dist/styles/ag-theme-alpine.css";
</style>

The code above presents two essential configuration properties of the grid - the column definitions (columnDefs) and the data (rowData). In our case, the column definitions contain three columns; column entry specifies the header label and the data field to be displayed in the body of the table.

Finally, note that we've imported the ag-grid-vue component - this is actual component that will provide the AG Grid functionality.

If everything works as expected, you should see a simple grid like the one on the screenshot:

AG Grid hello world

Enable Sorting And Filtering

So far, so good. But wouldn't it be nice to be able to sort the data to help us see which car is the least/most expensive? Well, enabling sorting in AG Grid is actually quite simple - all you need to do is set the sortable property to the column definitions.

this.columnDefs = [
    { field: 'make', sortable: true },
    { field: 'model', sortable: true },
    { field: 'price', sortable: true }
];

After adding the sortable property you should be able to sort the grid by clicking on the column headers. Clicking on a header toggles through ascending, descending and no-sort.

Our application doesn't have too many rows, so it's fairly easy to find data. But it's easy to imagine how a real-world application may have hundreds (or even hundreds of thousands!) of rows, with many columns. In a data set like this filtering is your friend.

As with sorting, enabling filtering is as easy as setting the filter property:

this.columnDefs = [
    { field: 'make', sortable: true, filter: true },
    { field: 'model', sortable: true, filter: true },
    { field: 'price', sortable: true, filter: true }
];

With this property set, the grid will display a small column menu icon when you hover the header. Pressing it will display a popup with a filtering UI which lets you choose the kind of filter and the text that you want to filter by.

AG Grid sorting and filtering

Fetch Remote Data

Displaying hard-coded data in JavaScript is not going to get us very far. In the real world, most of the time, we are dealing with data that resides on a remote server. Thanks to Vue, implementing this is actually quite simple. Notice that the actual data fetching is performed outside of the grid component - We are using the HTML5 fetch API.

Now, let's remove the hard-coded data and fetch it from a remote server. Edit the src/App.vue and add the following fetch statement:

beforeMount() {
    this.columnDefs = [
        { field: 'make' },
        { field: 'model' },
        { field: 'price' }
    ];

    fetch('https://www.ag-grid.com/example-assets/small-row-data.json')
        .then(result => result.json())
        .then(rowData => this.rowData = rowData);
}

The remote data is the same as the one we initially had, so you should not notice any actual changes to the grid. However, you will see an additional HTTP request performed if you open your developer tools.

Enable Selection

Being a programmer is a hectic job - just when we thought that we are done with our assignment, the manager shows up with a fresh set of requirements! It turned out that we need to allow the user to select certain rows from the grid and to mark them as flagged in the system. We will leave the flag toggle state and persistence to the backend team. On our side, we should enable the selection and, afterwards, to obtain the selected records and pass them with an API call to a remote service endpoint.

Fortunately the above task is quite simple with AG Grid. As you may have already guessed, it is just a matter of adding and changing couple of properties.

<template>
    <ag-grid-vue style="width: 500px; height: 500px;"
        class="ag-theme-alpine"
        :columnDefs="columnDefs"
        :rowData="rowData"
        rowSelection="multiple">
    </ag-grid-vue>
</template>
<script>
import {AgGridVue} from "ag-grid-vue";

export default {
   name: 'App',
   data() {
       return {
           columnDefs: null,
           rowData: null,
           gridApi: null,
           columnApi: null
       }
   },
   components: {
       AgGridVue
   },
   beforeMount() {
       this.columnDefs = [
           {field: 'make', sortable: true, filter: true, checkboxSelection: true},
           {field: 'model', sortable: true, filter: true},
           {field: 'price', sortable: true, filter: true}
       ];

       fetch('https://www.ag-grid.com/example-assets/small-row-data.json')
               .then(result => result.json())
               .then(rowData => this.rowData = rowData);
   }
}
</script>

<style lang="scss">
@import "../node_modules/ag-grid-community/dist/styles/ag-grid.css";
@import "../node_modules/ag-grid-community/dist/styles/ag-theme-alpine.css";
</style>

We've enabled multiple row selection by adding rowSelection="multiple", and we've also added a checkbox to the make column with checkboxSelection: true.

Vue AG Grid Selection

Great! Now the first column contains a checkbox that, when clicked, selects the row. The only thing we have to add is a button that gets the selected data and sends it to the server. To do this, we are going to use the AG Grid API - we will store a reference to both the grid and column API's in the gridReady event

To test this we'll add a button that gets the selected data and sends it to the server. Let's go ahead and make these changes:

<template>
    <div>
        <button @click="getSelectedRows()">Get Selected Rows</button>

        <ag-grid-vue style="width: 500px; height: 500px;"
            class="ag-theme-alpine"
            :columnDefs="columnDefs"
            :rowData="rowData"
            rowSelection="multiple"
            @grid-ready="onGridReady">
        </ag-grid-vue>
    </div>
</template>
<script>
    import { AgGridVue } from "ag-grid-vue";

    export default {
        name: 'App',
        data() {
            return {
                columnDefs: null,
                rowData: null
                gridApi: null,
                columnApi: null
            }
        },
        components: {
            AgGridVue
        },
        methods: {
            onGridReady(params) {
                this.gridApi = params.api;
                this.columnApi = params.columnApi;
            },
            getSelectedRows() {
                const selectedNodes = this.gridApi.getSelectedNodes();
                const selectedData = selectedNodes.map( node => node.data );
                const selectedDataStringPresentation = selectedData.map( node => `${node.make} ${node.model}`).join(', ');
                alert(`Selected nodes: ${selectedDataStringPresentation}`);
            }
        },
        beforeMount() {
            this.columnDefs = [
                { field: 'make', checkboxSelection: true },
                { field: 'model' },
                { field: 'price' }
            ];

            fetch('https://www.ag-grid.com/example-assets/small-row-data.json')
                .then(result => result.json())
                .then(rowData => this.rowData = rowData);
        }
    }
</script>

<style lang="scss">
@import "../node_modules/ag-grid-community/dist/styles/ag-grid.css";
@import "../node_modules/ag-grid-community/dist/styles/ag-theme-alpine.css";
</style>

Well, we cheated a bit. Calling alert is not exactly a call to our backend. Hopefully you will forgive us this shortcut for the sake of keeping the article short and simple. Of course, you can substitute that bit with a real-world application logic after you are done with the tutorial.

Grouping

Grouping is a feature exclusive to AG Grid Enterprise. You are free to trial AG Grid Enterprise to see what you think. You only need to get in touch if you want to start using AG Grid Enterprise in a project intended for production.

In addition to filtering and sorting, grouping is another effective way for the user to make sense out of large amounts of data.

Our current data set is pretty small so let's switch to a larger one:

- fetch('https://www.ag-grid.com/example-assets/small-row-data.json')
+ fetch('https://www.ag-grid.com/example-assets/row-data.json')

Let's enable the enterprise features of ag-grid. Install the additional package:

npm install --save ag-grid-enterprise

Then, add the import to src/main.js:

  import Vue from 'vue'

+ import 'ag-grid-enterprise';

  import App from './App'

After restarting the application you should see a message in the console that tells you there is no enterprise license key. You can ignore the message as we are trialing. In addition to that, the grid got a few UI improvements - a custom context menu and fancier column menu popup - feel free to look around:

AG Grid final

Now, let's enable grouping! Add an autoGroupColumnDef property, bind to it, and update the columnDefs with a rowGroup:

<template>
    <div>
        <button @click="getSelectedRows()">Get Selected Rows</button>
        <ag-grid-vue style="width: 500px; height: 500px;"
            class="ag-theme-alpine"
            :columnDefs="columnDefs"
            :rowData="rowData"
            :autoGroupColumnDef="autoGroupColumnDef"
            rowSelection="multiple"
            @grid-ready="onGridReady">
        </ag-grid-vue>
    </div>
</template>
<script>
    import { AgGridVue } from "ag-grid-vue";

    export default {
        name: 'App',
        data() {
            return {
                columnDefs: null,
                rowData: null,
                gridApi: null,
                columnApi: null,
                autoGroupColumnDef: null
            }
        },
        components: {
            AgGridVue
        },
        methods: {
            onGridReady(params) {
                this.gridApi = params.api;
                this.columnApi = params.columnApi;
            },
            getSelectedRows() {
                const selectedNodes = this.gridApi.getSelectedNodes();
                const selectedData = selectedNodes.map(node => node.data);
                const selectedDataStringPresentation = selectedData.map(node => `${node.make} ${node.model}`).join(', ');
                alert(`Selected nodes: ${selectedDataStringPresentation}`);
            }
        },
        beforeMount() {
            this.columnDefs = [
                { field: 'make', rowGroup: true },
                { field: 'model' },
                { field: 'price' }
            ];

            this.autoGroupColumnDef = {
                headerName: 'Model',
                field: 'model',
                cellRenderer: 'agGroupCellRenderer',
                cellRendererParams: {
                    checkbox: true
                }
            };

            fetch('https://www.ag-grid.com/example-assets/small-row-data.json')
                .then(result => result.json())
                .then(rowData => this.rowData = rowData);
        }
    }
</script>

<style lang="scss">
  @import "../node_modules/ag-grid-community/dist/styles/ag-grid.css";
  @import "../node_modules/ag-grid-community/dist/styles/ag-theme-alpine.css";
</style>

There we go! The grid now groups the data by make, while listing the model field value when expanded. Notice that grouping works with checkboxes as well - the groupSelectsChildren property adds a group-level checkbox that selects/deselects all items in the group.

Note that we also removed checkboxSelection: true from the make column definition as the autoGroupColumnDef definition allows for checkbox selection at both the group and leaf level.

Don't worry if this step feels a bit overwhelming - the grouping feature is very powerful and supports complex interaction scenarios which you might not need initially. The grouping documentation section contains plenty of real-world runnable examples that can get you started for your particular case.

Customise the Theme Look

The last thing which we are going to do is to change the grid look and feel by modifying some of the theme's Sass variables.

By default, AG Grid ships a set of pre-built theme stylesheets. If we want to tweak the colors and the fonts of theme, we should add a Sass preprocessor to our project, override the theme variable values, and refer the ag-grid Sass files instead of the pre-built stylesheets so that the variable overrides are applied.

The vue cli did a lot of for us including providing support for Sass. Let's switch to using the provided AG Grid SCSS files - replace the style block in src/App.vue with:

<style lang="scss">
  @import "../node_modules/ag-grid-community/src/styles/ag-grid.scss";
  @import "../node_modules/ag-grid-community/src/styles/ag-theme-alpine/sass/ag-theme-alpine-mixin.scss";

  .ag-theme-alpine {
      @include ag-theme-alpine((
          odd-row-background-color: #ACE
      ));
  }
</style>

If everything is configured correctly, the second row of the grid will be blue. Congratulations! You now know now bend the grid look to your will - there are a few dozens more Sass variables that let you control the font family and size, border color, header background color and even the amount of spacing in the cells and columns. The full Sass variable list is available in the themes documentation section.

Summary

With this tutorial, we managed to accomplish a lot. Starting from the humble beginnings of a three row / column setup, we now have a grid that supports sorting, filtering, binding to remote data, selection and even grouping! While doing so, we learned how to configure the grid, how to access its API object, and how to change the styling of the component.