Data binding in Vue Treegrid component

2 Sep 202524 minutes to read

The TreeGrid uses DataManager, which supports both RESTful JSON data services binding and local JavaScript object array binding. The dataSource property can be assigned either with the instance of DataManager or JavaScript object array collection.
It supports two kinds of data binding method:

  • Local data
  • Remote data

To learn about tree grid data binding quickly, you can check on this video:

Binding with ajax

You can use TreeGrid dataSource property to bind the data source to TreeGrid from external Fetch request. In the below code we have fetched the data source from the server with the help of Fetch request and provided that to dataSource property by using onSuccess event of the Fetch.

<template>
  <div id="app">
    <ejs-button v-on:click="btnClick">Bind Data</ejs-button>
        <ejs-treegrid ref=treegrid :dataSource="data" idMapping='TaskID' parentIdMapping='ParentItem'  :treeColumnIndex='1' :allowPaging='true' :pageSettings='pageSettings'>
            <e-columns>
                <e-column field='TaskID' headerText='Task ID' width='90' textAlign='Right'></e-column>
                <e-column field='TaskName' headerText='Task Name' width='100'></e-column>
                <e-column field='Duration' headerText='Duration' width='80' textAlign='Right'></e-column>
                <e-column field='Progress' headerText='Progress' width='80' textAlign='Right'></e-column>
                </e-columns>
        </ejs-treegrid>
</div>
</template>
<script setup>
import { provide } from "vue";

import { TreeGridComponent as EjsTreegrid, Page, ColumnDirective as EColumn, ColumnsDirective as EColumns } from "@syncfusion/ej2-vue-treegrid";
import { ButtonComponent as EjsButton } from "@syncfusion/ej2-vue-buttons";
import { Fetch } from '@syncfusion/ej2-base';

const data = {};
const pageSettings = { pageCount: 4 };

provide('treegrid',  [ Page ]);

const btnClick = function (){
        let treegrid = document.getElementsByClassName("e-treegrid")[0].ej2_instances[0]; // TreeGrid instance
        let fetch = new Fetch ("https://services.syncfusion.com/vue/production/api/SelfReferenceData", "GET");treegrid.showSpinner();
        fetch.send();
        fetch.onSuccess = function (result) {
        treegrid.hideSpinner();
        treegrid.dataSource = result;
        };
  };

</script>
<template>
  <div id="app">
    <ejs-button v-on:click="btnClick">Bind Data</ejs-button>
        <ejs-treegrid ref=treegrid :dataSource="data" idMapping='TaskID' parentIdMapping='ParentItem'  :treeColumnIndex='1' :allowPaging='true' :pageSettings='pageSettings'>
            <e-columns>
                <e-column field='TaskID' headerText='Task ID' width='90' textAlign='Right'></e-column>
                <e-column field='TaskName' headerText='Task Name' width='100'></e-column>
                <e-column field='Duration' headerText='Duration' width='80' textAlign='Right'></e-column>
                <e-column field='Progress' headerText='Progress' width='80' textAlign='Right'></e-column>
                </e-columns>
        </ejs-treegrid>
</div>
</template>
<script>

import { TreeGridComponent, Page, ColumnDirective, ColumnsDirective } from "@syncfusion/ej2-vue-treegrid";
import { ButtonComponent } from "@syncfusion/ej2-vue-buttons";
import { Fetch } from '@syncfusion/ej2-base';

export default {
name: "App",
components: {
"ejs-button":ButtonComponent,
"ejs-treegrid":TreeGridComponent,
"e-columns":ColumnsDirective,
"e-column":ColumnDirective,

},

  data () {
    return {
      data: {},
      pageSettings: { pageCount: 4 }
    };
  },
  provide: {
      treegrid: [ Page ]
    },
   methods:{
         btnClick: function (){
        let treegrid = document.getElementsByClassName("e-treegrid")[0].ej2_instances[0]; // TreeGrid instance
        let fetch = new Fetch ("https://services.syncfusion.com/vue/production/api/SelfReferenceData", "GET");treegrid.showSpinner();
        fetch.send();
        fetch.onSuccess = function (result) {
        treegrid.hideSpinner();
        treegrid.dataSource = result;
        };
      }
  }
}
</script>

  • If you bind the dataSource from this way, then it acts like a local dataSource. So you cannot perform any server side crud actions.

Handling expandStateMapping

To denotes the expand status of parent row, define the expandStateMapping property of tree grid. The expandStateMapping property maps the field name in data source, that denotes whether parent record is in expanded or collapsed state and this is useful to renders parent row in expanded or collapsed state based on this mapping property value in data source.

<template>
<div id="app">
        <ejs-treegrid :dataSource='data' idMapping='TaskID' parentIdMapping='ParentValue' hasChildMapping='isParent' :treeColumnIndex='1' expandStateMapping='IsExpanded' height='400px'>
        <e-columns>
        <e-column field='TaskID'  headerText='Task ID'  width=90 textAlign='Right'></e-column>
        <e-column field='TaskName' headerText='Task Name' width=180></e-column>
        <e-column field='Duration' headerText='Duration' width=80></e-column>
        </e-columns>
        </ejs-treegrid>
</div>
</template>
<script setup>

import { TreeGridComponent, Page } from "@syncfusion/ej2-vue-treegrid";
import { DataManager, UrlAdaptor } from '@syncfusion/ej2-data';




export default {
  data() {
    return {
      data: new DataManager({
        url: "Home/DataSource",
        adaptor: new UrlAdaptor
      })
    };
  },
}

</script>

The following code example defines expandStateMapping property at server end.

public ActionResult ExpandStateMapping()
{
  return View();
}
public class TreeData
{
    public static List<TreeData> tree = new List<TreeData>();
    [System.ComponentModel.DataAnnotations.Key]
    public int TaskID { get; set; }
    public string TaskName { get; set; }
    public int Duration { get; set; }
    public int? ParentValue { get; set; }
    public bool? isParent { get; set; }
    public bool IsExpanded { get; set; }
    public TreeData() { }
    public static List<TreeData> GetTree()
    {
        if (tree.Count == 0)
        {
            int root = 0;
            for (var t = 1; t <= 500; t++)
            {
                Random ran = new Random();
                string math = (ran.Next() % 3) == 0 ? "High" : (ran.Next() % 2) == 0 ? "Release Breaker" : "Critical";
                string progr = (ran.Next() % 3) == 0 ? "Started" : (ran.Next() % 2) == 0 ? "Open" : "In Progress";
                root++;
                int rootItem = root;
                tree.Add(new TreeData() { TaskID = rootItem, TaskName = "Parent task " + rootItem.ToString(), isParent = true, IsExpanded = false, ParentValue = null, Duration = ran.Next(1, 50) });
                int parent = root;
                for (var d = 0; d < 1; d++)
                {
                    root++;
                    string value = ((parent + 1) % 3 == 0) ? "Low" : "Critical";
                    int par = parent + 1;
                    progr = (ran.Next() % 3) == 0 ? "In Progress" : (ran.Next() % 2) == 0 ? "Open" : "Validated";
                    int iD = root;
                    tree.Add(new TreeData() { TaskID = iD, TaskName = "Child task " + iD.ToString(), isParent = true, IsExpanded = false, ParentValue = rootItem, Duration = ran.Next(1, 50) });
                    int subparent = root;
                    for (var c = 0; c < 500; c++)
                    {
                        root++;
                        string val = ((subparent + c + 1) % 3 == 0) ? "Low" : "Critical";
                        int subchild = subparent + c + 1;
                        string progress = (ran.Next() % 3) == 0 ? "In Progress" : (ran.Next() % 2) == 0 ? "Open" : "Validated";
                        int childID = root ;
                        tree.Add(new TreeData() { TaskID = childID, TaskName = "sub Child task " + childID.ToString(), isParent = false, IsExpanded = false, ParentValue = subparent, Duration = ran.Next(1, 50) });
                    }
                }
            }
        }
        return tree;
    }
}

Custom binding

It is possible to handle data processing externally and bind the result to the TreeGrid. This helps you to provide your own custom data logic. TreeGrid expects an object as the result of the custom logic and the emitted value should be an object with properties result and count.

In this context, we are going to use DataManager with WebApi Adaptor for handling remote interaction, you can choose any HTTP client as per your choice.

We have a limitation for Custom Binding feature of TreeGrid. This feature works only for Self Referential data binding with pageSizeMode as Root.

Handling child data

Using the custom binding feature you can bind the child data for a parent record as per your custom logic. When a parent record is expanded, dataStateChange event is triggered in which you can assign your custom data to the childData property of the dataStateChange event arguments.
After assigning the child data, childDataBind method should be called from the
dataStateChange event arguments to indicate that the data is bound.

In this context, initially we have assigned only the parent records to the treegrid dataSource and fetched the required child records in the dataStateChange event.

Handling Tree Grid actions

For TreeGrid actions such as paging, sorting, etc dataStateChange event will be invoked. You have to query and resolve data using Fetch in this event based on the state arguments.

Performing CRUD actions

The dataSourceChanged event will be triggered for updating the treegrid data. You can perform the save operation based on the event arguments and call the endEdit method to indicate the completion of save operation.

Calculate aggregates

The footer aggregate values should be calculated and sent along with the dataSource property as follows. The aggregate property of the data source should contain the aggregate value assigned to the property named in the field – type format. For example, the Sum aggregate value for the Duration field should be assigned to the property named as Duration - sum.

{
result: [{..}, {..}, {..}, …],
count: 830,
aggregates: { ‘Freight - sum’ : 450,’EmployeeID - min’: 1 }
}

Provide excel filter data source

The dataStateChange event will be triggered with appropriate arguments when the excel filter requests the filter choice data source. You need to resolve the excel filter data source using the dataSource resolver function from the state argument as follows.