Context menu in Vue Treegrid component

11 Jun 202424 minutes to read

The TreeGrid has options to show the context menu when right clicked on it. To enable this feature, you need to define either default or custom item in the contextMenuItems.

To use the context menu, inject the ContextMenu module in the treegrid.

The default items are in the following table.

Items Description
AutoFit Auto fit the current column.
AutoFitAll Auto fit all columns.
Edit Edit the current record.
Delete Delete the current record.
Save Save the edited record.
Cancel Cancel the edited state.
PdfExport Export the treegrid data as Pdf document.
ExcelExport Export the treegrid data as Excel document.
CsvExport Export the treegrid data as CSV document.
SortAscending Sort the current column in ascending order.
SortDescending Sort the current column in descending order.
FirstPage Go to the first page.
PrevPage Go to the previous page.
LastPage Go to the last page.
NextPage Go to the next page.
AddRow Add new row to the treegrid.
Indent Indents the record to one level of hierarchy.
Outdent Outdents the record to one level of hierarchy.
<template>
<div id="app">
        <ejs-treegrid :dataSource='data' childMapping='subtasks' :treeColumnIndex='1' :allowPaging='true' :pageSettings='pageSettings' :allowSorting='true' :allowResizing='true' :editSettings='editSettings' :allowPdfExport='true' :allowExcelExport='true' :contextMenuItems="contextMenuItems">
            <e-columns>
                <e-column field='taskID' headerText='Task ID' width='90' textAlign='Right'></e-column>
                <e-column field='taskName' headerText='Task Name' width='160'></e-column>
                <e-column field='startDate' headerText='Start Date' width='90' format="yMd" textAlign='Right'></e-column>
                <e-column field='duration' headerText='Duration' width='80' textAlign='Right'></e-column>
            </e-columns>
        </ejs-treegrid>
</div>
</template>
<script setup>
import { provide } from "vue";

import { TreeGridComponent as EjsTreegrid, Resize, Sort, ContextMenu, Edit, Page, PdfExport, ExcelExport, ColumnDirective as EColumn, ColumnsDirective as EColumns } from "@syncfusion/ej2-vue-treegrid";
import { sampleData } from "./datasource.js";

const data = sampleData;

const editSettings = { allowEditing: true, allowAdding: true, allowDeleting: true };

const pageSettings = { pageSize: 7 };

const contextMenuItems = ['AutoFit', 'AutoFitAll', 'SortAscending', 'SortDescending',
        'Copy', 'Edit', 'Delete', 'Save', 'Cancel',
        'PdfExport', 'ExcelExport', 'CsvExport', 'FirstPage', 'PrevPage',
        'LastPage', 'NextPage', 'Group', 'Ungroup', 'Indent', 'Outdent'
];

provide('treegrid',  [ Resize, Sort, ContextMenu, Edit, Page, PdfExport, ExcelExport ]);

</script>
<template>
<div id="app">
        <ejs-treegrid :dataSource='data' childMapping='subtasks' :treeColumnIndex='1' :allowPaging='true' :pageSettings='pageSettings' :allowSorting='true' :allowResizing='true' :editSettings='editSettings' :allowPdfExport='true' :allowExcelExport='true' :contextMenuItems="contextMenuItems">
            <e-columns>
                <e-column field='taskID' headerText='Task ID' width='90' textAlign='Right'></e-column>
                <e-column field='taskName' headerText='Task Name' width='160'></e-column>
                <e-column field='startDate' headerText='Start Date' width='90' format="yMd" textAlign='Right'></e-column>
                <e-column field='duration' headerText='Duration' width='80' textAlign='Right'></e-column>
            </e-columns>
        </ejs-treegrid>
</div>
</template>
<script>

import { TreeGridComponent, Resize, Sort, ContextMenu, Edit, Page, PdfExport, ExcelExport, ColumnDirective, ColumnsDirective } from "@syncfusion/ej2-vue-treegrid";
import { sampleData } from "./datasource.js";



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

},

  data ()  {
    return {
      data: sampleData,
      editSettings: { allowEditing: true, allowAdding: true, allowDeleting: true },
      pageSettings: { pageSize: 7 },
      contextMenuItems: ['AutoFit', 'AutoFitAll', 'SortAscending', 'SortDescending',
        'Copy', 'Edit', 'Delete', 'Save', 'Cancel',
        'PdfExport', 'ExcelExport', 'CsvExport', 'FirstPage', 'PrevPage',
        'LastPage', 'NextPage', 'Group', 'Ungroup', 'Indent', 'Outdent'],
    };
  },
  provide: {
      treegrid: [ Resize, Sort, ContextMenu, Edit, Page, PdfExport, ExcelExport ]
    }
}
</script>

Custom context menu items

The custom context menu items can be added by defining the contextMenuItems as a collection of
contextMenuItemModel.
Actions for this customized items can be defined in the contextMenuClick event.

In the below sample, we have shown context menu item for parent rows to expand or collapse child rows.

<template>
<div id="app">
        <ejs-treegrid ref='treegrid' :dataSource='data' childMapping='subtasks' :treeColumnIndex='1' :allowPaging='true' :pageSettings='pageSettings' :contextMenuItems="contextMenuItems" :contextMenuOpen='contextMenuOpen' :contextMenuClick='contextMenuClick'>
            <e-columns>
                <e-column field='taskID' headerText='Task ID' width='90' textAlign='Right'></e-column>
                <e-column field='taskName' headerText='Task Name' width='160'></e-column>
                <e-column field='startDate' headerText='Start Date' width='90' format="yMd" textAlign='Right'></e-column>
                <e-column field='duration' headerText='Duration' width='80' textAlign='Right'></e-column>
            </e-columns>
        </ejs-treegrid>
</div>
</template>
<script setup>
import { provide, ref } from "vue";

import { TreeGridComponent as EjsTreegrid, ContextMenu, Page, ColumnDirective as EColumn, ColumnsDirective as EColumns  } from "@syncfusion/ej2-vue-treegrid";
import { sampleData } from "./datasource.js";
import { getValue, isNullOrUndefined } from '@syncfusion/ej2-base';

const treegrid = ref(null);
const data = sampleData;

const pageSettings = { pageSize: 7 };

const contextMenuItems = [
    {text: 'Collapse the Row', target: '.e-content', id: 'collapserow'},
    {text: 'Expand the Row', target: '.e-content', id: 'expandrow'}
];

provide('treegrid',  [ ContextMenu, Page ]);

const contextMenuOpen = function (arg) {
    let elem = arg.event.target;
    let uid = (elem.closest('.e-row')).getAttribute('data-uid');
    if (isNullOrUndefined(getValue('hasChildRecords', treegrid.value.ej2Instances.grid.getRowObjectFromUID(uid).data))) {
        arg.cancel = true;
    } else {
      let flag = getValue('expanded', treegrid.value.ej2Instances.grid.getRowObjectFromUID(uid).data);
      let val = flag ? 'none' : 'block';
      document.querySelectorAll('li#expandrow')[0].setAttribute('style', 'display: ' + val + ';');
      val = !flag ? 'none' : 'block';
      document.querySelectorAll('li#collapserow')[0].setAttribute('style', 'display: ' + val + ';');
    }
};

const contextMenuClick = function (args) {
    let selectedRows = treegrid.value.getSelectedRows();
    let selectedRecords = treegrid.value.getSelectedRecords();
    if (args.item.id === 'collapserow') {
      treegrid.value.collapseRow(selectedRows[0], selectedRecords[0]);
    } else {
      treegrid.value.expandRow(selectedRows[0], selectedRecords[0]);
    }
};

</script>
<template>
<div id="app">
        <ejs-treegrid ref='treegrid' :dataSource='data' childMapping='subtasks' :treeColumnIndex='1' :allowPaging='true' :pageSettings='pageSettings' :contextMenuItems="contextMenuItems" :contextMenuOpen='contextMenuOpen' :contextMenuClick='contextMenuClick'>
            <e-columns>
                <e-column field='taskID' headerText='Task ID' width='90' textAlign='Right'></e-column>
                <e-column field='taskName' headerText='Task Name' width='160'></e-column>
                <e-column field='startDate' headerText='Start Date' width='90' format="yMd" textAlign='Right'></e-column>
                <e-column field='duration' headerText='Duration' width='80' textAlign='Right'></e-column>
            </e-columns>
        </ejs-treegrid>
</div>
</template>
<script>

import { TreeGridComponent, ContextMenu, Page, ColumnDirective, ColumnsDirective } from "@syncfusion/ej2-vue-treegrid";
import { sampleData } from "./datasource.js";
import { getValue, isNullOrUndefined } from '@syncfusion/ej2-base';



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

},

  data ()  {
    return {
      data: sampleData,
      pageSettings: { pageSize: 7 },
      contextMenuItems: [
          {text: 'Collapse the Row', target: '.e-content', id: 'collapserow'},
          {text: 'Expand the Row', target: '.e-content', id: 'expandrow'}
      ],
    };
  },
  provide: {
      treegrid: [ ContextMenu, Page ]
  },
  methods:{
      contextMenuOpen:function (arg) {
        let elem = arg.event.target;
        let uid = (elem.closest('.e-row')).getAttribute('data-uid');
        if (isNullOrUndefined(getValue('hasChildRecords', this.$refs.treegrid.ej2Instances.grid.getRowObjectFromUID(uid).data))) {
            arg.cancel = true;
        } else {
          let flag = getValue('expanded', this.$refs.treegrid.ej2Instances.grid.getRowObjectFromUID(uid).data);
          let val = flag ? 'none' : 'block';
          document.querySelectorAll('li#expandrow')[0].setAttribute('style', 'display: ' + val + ';');
          val = !flag ? 'none' : 'block';
          document.querySelectorAll('li#collapserow')[0].setAttribute('style', 'display: ' + val + ';');
        }
      },
      contextMenuClick:function (args) {
        let selectedRows = this.$refs.treegrid.getSelectedRows()
        let selectedRecords = this.$refs.treegrid.getSelectedRecords()
        if (args.item.id === 'collapserow') {
          this.$refs.treegrid.collapseRow(selectedRows[0], selectedRecords[0]);
        } else {
          this.$refs.treegrid.expandRow(selectedRows[0], selectedRecords[0]);
        }
      }
  }
}
</script>

Enable and disable context menu items dynamically

You can enable and disable the context menu items using the enableItems method in contextMenuOpen event.

<template>
<div id="app">
        <ejs-treegrid ref='treegrid' :dataSource='data' childMapping='subtasks' :treeColumnIndex='1' :editSettings='editSettings' :allowPaging='true' :pageSettings='pageSettings' :contextMenuItems="contextMenuItems" :contextMenuOpen='contextMenuOpen' :contextMenuClick='contextMenuClick'>
            <e-columns>
                <e-column field='taskID' headerText='Task ID' width='90' textAlign='Right'></e-column>
                <e-column field='taskName' headerText='Task Name' width='160'></e-column>
                <e-column field='startDate' headerText='Start Date' width='90' format="yMd" textAlign='Right'></e-column>
                <e-column field='duration' headerText='Duration' width='80' textAlign='Right'></e-column>
            </e-columns>
        </ejs-treegrid>
</div>
</template>

<script setup>
import { provide, ref } from "vue";

import { TreeGridComponent as EjsTreegrid, ContextMenu, Page, Edit, ColumnDirective as EColumn, ColumnsDirective as EColumns  } from "@syncfusion/ej2-vue-treegrid";
import { sampleData } from "./datasource.js";

const treegrid = ref(null);

const data = sampleData;

const editSettings = { allowDeleting: true, allowEditing: true, allowAdding: true, mode: 'Row' };

const pageSettings = { pageSize: 7 };

const contextMenuItems = [
    {text: 'Edit Record', target: '.e-content', id: 'Edit_record'},
    { text: 'Delete Record', target: '.e-content', id: 'Delete_record' },
];

const contextMenuOpen = function (args) {
    if (args.rowInfo.rowData.hasChildRecords == true) {
      treegrid.value.ej2Instances.grid.contextMenuModule.contextMenu.enableItems(['Edit Record'],true);
      treegrid.value.ej2Instances.grid.contextMenuModule.contextMenu.enableItems(['Delete Record'],false);
    } else  {
      treegrid.value.ej2Instances.grid.contextMenuModule.contextMenu.enableItems(['Edit Record'],false);
      treegrid.value.ej2Instances.grid.contextMenuModule.contextMenu.enableItems(['Delete Record'],true);
    }
};

const contextMenuClick = function (args) {
    if(args.element.innerHTML == "Edit Record"){
        treegrid.value.ej2Instances.grid.editModule.startEdit(args.rowInfo.row);
    }
    else if(args.element.innerHTML == "Delete Record"){
         treegrid.value.ej2Instances.grid.editModule.deleteRecord(args.rowInfo.row);
    }
};

provide('treegrid',  [ ContextMenu, Page, Edit ]);

</script>
<template>
<div id="app">
        <ejs-treegrid ref='treegrid' :dataSource='data' childMapping='subtasks' :treeColumnIndex='1' :editSettings='editSettings' :allowPaging='true' :pageSettings='pageSettings' :contextMenuItems="contextMenuItems" :contextMenuOpen='contextMenuOpen' :contextMenuClick='contextMenuClick'>
            <e-columns>
                <e-column field='taskID' headerText='Task ID' width='90' textAlign='Right'></e-column>
                <e-column field='taskName' headerText='Task Name' width='160'></e-column>
                <e-column field='startDate' headerText='Start Date' width='90' format="yMd" textAlign='Right'></e-column>
                <e-column field='duration' headerText='Duration' width='80' textAlign='Right'></e-column>
            </e-columns>
        </ejs-treegrid>
</div>
</template>

<script>

import { TreeGridComponent, ContextMenu, Page, Edit, ColumnDirective, ColumnsDirective  } from "@syncfusion/ej2-vue-treegrid";
import { sampleData } from "./datasource.js";

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

},

  data ()  {
    return {
      data: sampleData,
      editSettings: { allowDeleting: true, allowEditing: true, allowAdding: true, mode: 'Row' },
      pageSettings: { pageSize: 7 },
      contextMenuItems: [
          {text: 'Edit Record', target: '.e-content', id: 'Edit_record'},
          { text: 'Delete Record', target: '.e-content', id: 'Delete_record' },
      ],
    };
  },
  provide: {
      treegrid: [ ContextMenu, Page, Edit ]
  },
  methods:{
      contextMenuOpen:function (args) {
        if (args.rowInfo.rowData.hasChildRecords == true) {
          this.$refs.treegrid.ej2Instances.grid.contextMenuModule.contextMenu.enableItems(['Edit Record'],true);
          this.$refs.treegrid.ej2Instances.grid.contextMenuModule.contextMenu.enableItems(['Delete Record'],false);
        } else  {
          this.$refs.treegrid.ej2Instances.grid.contextMenuModule.contextMenu.enableItems(['Edit Record'],false);
          this.$refs.treegrid.ej2Instances.grid.contextMenuModule.contextMenu.enableItems(['Delete Record'],true);
        }
      },
      contextMenuClick:function (args) {
        if(args.element.innerHTML == "Edit Record"){
            this.$refs.treegrid.ej2Instances.grid.editModule.startEdit(args.rowInfo.row);
        }
        else if(args.element.innerHTML == "Delete Record"){
             this.$refs.treegrid.ej2Instances.grid.editModule.deleteRecord(args.rowInfo.row);
        }
      }
  }
}
</script>

You can hide or show an item in context menu for specific area inside of treegrid by defining the target property.