---
title: "Context"
framework: vue
version: "36.1.0"
---

# Context

This sections covers how shared contextual information can be passed around the grid.

## Overview

The context object is passed to all callbacks and events used in the grid. The purpose of the context object is to allow the client application to pass details to custom callbacks such as the [Cell Renderers](https://www.ag-grid.com/vue-data-grid/component-cell-renderer/) and [Cell Editors](https://www.ag-grid.com/vue-data-grid/cell-editing/).

| Property | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `context` | `any` |  |  | Provides a context object that is provided to different callbacks the grid uses. Used for passing additional information to the callbacks used by your application. [Initial](https://www.ag-grid.com/vue-data-grid/grid-interface/#initial-grid-options). |

To update the context call `api.setGridOption` with the new context. Alternatively, if you maintain a reference to the context object it's values can be mutated directly.

## Context Object Example

The example below demonstrates how the context object can be used. Note the following:

- Selecting the reporting currency from the dropdown places it in the context object.
- When the reporting currency is changed the cell renderer uses the currency supplied in the context object to calculate the value using: `params.context.reportingCurrency`.
- The price column header is updated to show the selected currency using a header value getter using `ctx.reportingCurrency`.

#### Context Object

```ts
import {
  createApp,
  defineComponent,
  onBeforeMount,
  ref,
  shallowRef,
} from "vue";
import { AgGridVue } from "ag-grid-vue3";
import {
  ClientSideRowModelModule,
  ColDef,
  ColGroupDef,
  GridApi,
  GridOptions,
  GridReadyEvent,
  HighlightChangesModule,
  ICellRendererParams,
  ModuleRegistry,
  RenderApiModule,
  ValueGetterParams,
  enableDevValidations,
} from "ag-grid-community";
if (process.env.NODE_ENV !== "production") {
  enableDevValidations();
}

ModuleRegistry.registerModules([
  RenderApiModule,
  HighlightChangesModule,
  ClientSideRowModelModule,
]);

const gbpFormatter = new Intl.NumberFormat("en-US", {
  style: "currency",
  currency: "GBP",
  minimumFractionDigits: 2,
});

const eurFormatter = new Intl.NumberFormat("en-US", {
  style: "currency",
  currency: "EUR",
  minimumFractionDigits: 2,
});

const usdFormatter = new Intl.NumberFormat("en-US", {
  style: "currency",
  currency: "USD",
  minimumFractionDigits: 2,
});

const currencyComparator = (a: any, b: any) => {
  return a.amount - b.amount;
};

const currencyCellRenderer = (params: ICellRendererParams) => {
  switch (params.value.currency) {
    case "EUR":
      return eurFormatter.format(params.value.amount);
    case "USD":
      return usdFormatter.format(params.value.amount);
    case "GBP":
      return gbpFormatter.format(params.value.amount);
  }
  return params.value.amount;
};

function reportingCurrencyValueGetter(params: ValueGetterParams) {
  // Rates taken from google at time of writing
  const exchangeRates: Record<string, any> = {
    EUR: {
      GBP: 0.72,
      USD: 1.08,
    },
    GBP: {
      EUR: 1.29,
      USD: 1.5,
    },
    USD: {
      GBP: 0.67,
      EUR: 0.93,
    },
  };
  const price = params.data[params.colDef.field!];
  const reportingCurrency = params.context.reportingCurrency;
  const fxRateSet = exchangeRates[reportingCurrency];
  const fxRate = fxRateSet[price.currency];
  let priceInReportingCurrency;
  if (fxRate) {
    priceInReportingCurrency = price.amount * fxRate;
  } else {
    priceInReportingCurrency = price.amount;
  }
  const result = {
    currency: reportingCurrency,
    amount: priceInReportingCurrency,
  };
  return result;
}

function getData() {
  return [
    { product: "Product 1", price: { currency: "EUR", amount: 644 } },
    { product: "Product 2", price: { currency: "EUR", amount: 354 } },
    { product: "Product 3", price: { currency: "GBP", amount: 429 } },
    { product: "Product 4", price: { currency: "GBP", amount: 143 } },
    { product: "Product 5", price: { currency: "USD", amount: 345 } },
    { product: "Product 6", price: { currency: "USD", amount: 982 } },
  ];
}

const VueExample = defineComponent({
  template: `
        <div style="height: 100%">
                <div style="height: 10%">
      <select id="currency" v-on:change="currencyChanged()">
        <option value="EUR">EUR</option>
        <option value="GBP">GBP</option>
        <option value="USD">USD</option>
      </select>
    </div>
    <ag-grid-vue
      style="width: 100%; height: 90%;"
      @grid-ready="onGridReady"
      :columnDefs="columnDefs"
      :defaultColDef="defaultColDef"
      :rowData="rowData"
      :context="context"></ag-grid-vue>
        </div>
    `,
  components: {
    "ag-grid-vue": AgGridVue,
  },
  setup(props) {
    const gridApi = shallowRef<GridApi | null>(null);
    const columnDefs = ref<ColDef[]>([
      { field: "product" },
      { headerName: "Currency", field: "price.currency" },
      {
        headerName: "Price Local",
        field: "price",
        cellRenderer: currencyCellRenderer,
        comparator: currencyComparator,
        cellDataType: false,
      },
      {
        headerName: "Report Price",
        field: "price",
        cellRenderer: currencyCellRenderer,
        comparator: currencyComparator,
        valueGetter: reportingCurrencyValueGetter,
        headerValueGetter: "ctx.reportingCurrency",
      },
    ]);
    const defaultColDef = ref<ColDef>({
      flex: 1,
      enableCellChangeFlash: true,
    });
    const rowData = ref<any[] | null>(getData());
    const context = ref<any>({
      reportingCurrency: "EUR",
    });

    function currencyChanged() {
      const value = (document.getElementById("currency") as any).value;
      gridApi.value.setGridOption("context", { reportingCurrency: value });
      gridApi.value!.refreshCells();
      gridApi.value!.refreshHeader();
    }
    const onGridReady = (params: GridReadyEvent) => {
      gridApi.value = params.api;
    };

    return {
      gridApi,
      columnDefs,
      defaultColDef,
      rowData,
      context,
      onGridReady,
      currencyChanged,
    };
  },
});

const app = createApp(VueExample);
app.mount("#app");
```

[Live example: Context Object](https://www.ag-grid.com/examples/context/context/vue3)

## Context & Expressions Example

Below shows a complex example making use of value getters (using expressions) and class rules (again using expressions). The grid shows 'actual vs budget data and yearly total' for widget sales split by city and country.

- The **Location** column is showing the aggregation groups, grouping by city and country.
- The **Monthly Data** columns are affected by the context. Depending on the selected period, the data displayed is either actual (`x_act`) or budgeted (`x_bud`) data for the month (eg. `jan_act` when Jan is green, or `jan_bud` when Jan is red). Similarly, the background color is also changed using class rules dependent on the selected period.
- **sum(YTD)** is the total of the 'actual' figures, i.e. adding up all the green. This also changes as the period is changed.

Notice that the example (including calculating the expression on the fly, the grid only calculates what's needed to be displayed) runs very fast (once the data is loaded) despite having over 6,000 rows.

This example is best viewed by opening it in a new tab.

#### Monthly Sales

```ts
import {
  createApp,
  defineComponent,
  onBeforeMount,
  ref,
  shallowRef,
} from "vue";

import type {
  ColDef,
  ColGroupDef,
  GridApi,
  GridReadyEvent,
  ICellRendererParams,
  RowSelectionOptions,
} from "ag-grid-community";
import {
  CellStyleModule,
  ClientSideRowModelApiModule,
  ClientSideRowModelModule,
  ModuleRegistry,
  QuickFilterModule,
  RenderApiModule,
  RowSelectionModule,
  enableDevValidations,
} from "ag-grid-community";
import {
  FiltersToolPanelModule,
  RowGroupingModule,
  SetFilterModule,
} from "ag-grid-enterprise";
import { AgGridVue } from "ag-grid-vue3";

import "./styles.css";

// Enable extended validations only for development
if (process.env.NODE_ENV !== "production") {
  enableDevValidations();
}

ModuleRegistry.registerModules([
  ClientSideRowModelApiModule,
  RenderApiModule,
  RowSelectionModule,
  CellStyleModule,
  ClientSideRowModelModule,
  QuickFilterModule,
  RowGroupingModule,
  SetFilterModule,
  FiltersToolPanelModule,
]);

const VueExample = defineComponent({
  template: `
        <div style="height: 100%">
            <div class="test-container">
                <div class="test-header">
                    <input type="text" id="filter-text-box" style="width: 100px;" v-on:input="onQuickFilterChanged()" placeholder="Filter...">
                    <span style="padding-left: 20px;">
                        <b>Period:</b>
                        <button v-on:click="onChangeMonth(-1)"><i class="fa fa-chevron-left"></i></button>
                        <button v-on:click="onChangeMonth(1)"><i class="fa fa-chevron-right"></i></button>
                        <span id="monthName" style="width: 100px; display: inline-block;">Year to Jan</span>
                    </span>
                    <span style="padding-left: 20px;">
                        <b>Legend:</b>&nbsp;&nbsp;
                        <div class="cell-bud legend-box"></div> Actual&nbsp;&nbsp;
                        <div class="cell-act legend-box"></div> Budget
                    </span>
                </div>
                <ag-grid-vue
                
                style="width: 100%; height: 100%;"
                :columnDefs="columnDefs"
                :suppressMovableColumns="true"
                @grid-ready="onGridReady"
                :context="context"
                :defaultColDef="defaultColDef"
                :autoGroupColumnDef="autoGroupColumnDef"
                :rowSelection="rowSelection"
                :rowData="rowData"></ag-grid-vue></div>
        </div>
    `,
  components: {
    "ag-grid-vue": AgGridVue,
  },
  setup(props) {
    const columnDefs = ref<(ColDef | ColGroupDef)[]>([
      { field: "country", rowGroup: true, hide: true },
      {
        headerName: "Monthly Data",
        children: [
          {
            field: "jan",
            cellRenderer: accountingCellRenderer,
            cellClass: "cell-figure",
            valueGetter: monthValueGetter,
            cellClassRules: monthCellClassRules,
            aggFunc: "sum",
          },
          {
            field: "feb",
            cellRenderer: accountingCellRenderer,
            cellClass: "cell-figure",
            valueGetter: monthValueGetter,
            cellClassRules: monthCellClassRules,
            aggFunc: "sum",
          },
          {
            field: "mar",
            cellRenderer: accountingCellRenderer,
            cellClass: "cell-figure",
            valueGetter: monthValueGetter,
            cellClassRules: monthCellClassRules,
            aggFunc: "sum",
          },
          {
            field: "apr",
            cellRenderer: accountingCellRenderer,
            cellClass: "cell-figure",
            valueGetter: monthValueGetter,
            cellClassRules: monthCellClassRules,
            aggFunc: "sum",
          },
          {
            field: "may",
            cellRenderer: accountingCellRenderer,
            cellClass: "cell-figure",
            valueGetter: monthValueGetter,
            cellClassRules: monthCellClassRules,
            aggFunc: "sum",
          },
          {
            field: "jun",
            cellRenderer: accountingCellRenderer,
            cellClass: "cell-figure",
            valueGetter: monthValueGetter,
            cellClassRules: monthCellClassRules,
            aggFunc: "sum",
          },
          {
            headerName: "YTD",
            cellClass: "cell-figure",
            cellRenderer: accountingCellRenderer,
            valueGetter: yearToDateValueGetter,
            aggFunc: "sum",
          },
        ],
      },
    ]);
    const gridApi = shallowRef<GridApi | null>(null);
    const defaultColDef = ref<ColDef>({
      flex: 1,
      minWidth: 120,
    });
    const context = ref(null);
    const autoGroupColumnDef = ref<ColDef>(null);
    const rowData = ref<any[]>(null);
    const rowSelection = ref<RowSelectionOptions>(null);

    onBeforeMount(() => {
      context.value = {
        month: 0,
        months: [
          "jan",
          "feb",
          "mar",
          "apr",
          "may",
          "jun",
          "jul",
          "aug",
          "sep",
          "oct",
          "nov",
          "dec",
        ],
      };
      autoGroupColumnDef.value = {
        headerName: "Location",
        field: "city",
        minWidth: 260,
        cellRenderer: "agGroupCellRenderer",
      };
      rowSelection.value = {
        mode: "multiRow",
        headerCheckbox: false,
        groupSelects: "descendants",
      };
    });

    const onChangeMonth = (i) => {
      var newMonth = (context.value.month += i);
      if (newMonth < -1) {
        newMonth = -1;
      }
      if (newMonth > 5) {
        newMonth = 5;
      }
      // Mutate the context object in place
      context.value.month = newMonth;
      document.querySelector("#monthName").textContent =
        monthNames[newMonth + 1];
      gridApi.value.refreshClientSideRowModel("aggregate");
      gridApi.value.refreshCells();
    };
    const onQuickFilterChanged = () => {
      gridApi.value.setGridOption(
        "quickFilterText",
        document.getElementById("filter-text-box").value,
      );
    };
    const onGridReady = (params: GridReadyEvent) => {
      gridApi.value = params.api;

      const updateData = (data) => {
        rowData.value = data;
      };

      fetch("https://www.ag-grid.com/example-assets/monthly-sales.json")
        .then((resp) => resp.json())
        .then((data) => updateData(data));
    };

    return {
      columnDefs,
      gridApi,
      context,
      defaultColDef,
      autoGroupColumnDef,
      rowSelection,
      rowData,
      onGridReady,
      onChangeMonth,
      onQuickFilterChanged,
    };
  },
});

var monthValueGetter =
  '(ctx.month < ctx.months.indexOf(colDef.field)) ? data[colDef.field + "_bud"] : data[colDef.field + "_act"]';

var monthCellClassRules = {
  "cell-act": "ctx.month < ctx.months.indexOf(colDef.field)",
  "cell-bud": "ctx.month >= ctx.months.indexOf(colDef.field)",
  "cell-negative": "x < 0",
};

var yearToDateValueGetter =
  'var total = 0; ctx.months.forEach( function(monthName, monthIndex) { if (monthIndex<=ctx.month) { total += data[monthName + "_act"]; } }); return total; ';

var accountingCellRenderer = function (params: ICellRendererParams) {
  if (params.value == null) {
    return "";
  } else if (params.value >= 0) {
    return params.value.toLocaleString();
  } else {
    return "(" + Math.abs(params.value).toLocaleString() + ")";
  }
};

var monthNames = [
  "Budget Only",
  "Year to Jan",
  "Year to Feb",
  "Year to Mar",
  "Year to Apr",
  "Year to May",
  "Year to Jun",
  "Year to Jul",
  "Year to Aug",
  "Year to Sep",
  "Year to Oct",
  "Year to Nov",
  "Full Year",
];

createApp(VueExample).mount("#app");
```

[Live example: Monthly Sales](https://www.ag-grid.com/examples/context/monthly-sales/vue3)
