Vue UI Components Documentation
With GraphQL, the client says exactly which fields it wants and sends its arguments as typed variables. This tutorial connects a jqxGrid in a Vue 3 app to a GraphQL API with nothing but fetch: a query brings one page of orders, sorted and filtered on the server, and a mutation saves each edit. It builds the API too, with GraphQL Yoga on Node.js; the grid's side works the same with any GraphQL server, such as Apollo Server, Hasura or a .NET or Java one.

You need Node.js 22 or later for the API. Create a project for it and install GraphQL Yoga:
npm init -y
npm install graphql graphql-yoga
npm pkg set type=module
The app is a Vite, Vue 3.5 and TypeScript app with jqwidgets-scripts, set up as in Add a Grid to a Vue 3 app. It needs no GraphQL client library. Before jqwidgets-scripts 27.1.0 the Grid needs two settings in vite.config.ts; they do no harm in 27.1.0:
import vue from '@vitejs/plugin-vue';
import { defineConfig, type Plugin } from 'vite';
// Before jqwidgets-scripts 27.1.0: globalize.js, which the Grid component imports, hands its code
// `this` as the window. In an ES module `this` is undefined, and the dev server serves the file
// as one, so `npm run dev` stops with "Cannot set properties of undefined (setting 'Globalize')".
// (The production build is not affected.) This passes the window instead; with 27.1.0 it changes nothing.
const globalizeWindow: Plugin = {
name: 'jqwidgets-globalize-window',
transform(code, id) {
if (id.includes('jqwidgets-scripts/jqwidgets/globalization/globalize.js')) {
return code.replace(/\}\(this\)\);/, '}(window));');
}
}
};
export default defineConfig({
plugins: [vue(), globalizeWindow],
// Some jqWidgets themes still carry Internet Explorer CSS hacks (*zoom: 1; in 27.1.0 only light-ie
// and dark-ie), which Vite's CSS minifier rejects; errorRecovery drops those lines instead of
// failing the build.
css: { lightningcss: { errorRecovery: true } }
});
The plugin is for npm run dev: the Grid component imports globalize.js, which before 27.1.0 passes this to its code as the window. The dev server serves the file as an ES module, where this is undefined, and the app stops with Cannot set properties of undefined (setting 'Globalize'). With 27.1.0 the plugin changes nothing. errorRecovery is for npm run build, which otherwise fails on the old browser hacks (*zoom: 1) of some theme files (in 27.1.0 only light-ie and dark-ie have them).
Save this as server.js and start it with node server.js. The schema is the contract between the grid and the server: an orders query with an offset, a page size, a sort and a list of filters, which returns the rows of the page and the number of matching orders, and an updateOrder mutation.
// A GraphQL API for the grid: orders a page at a time, sorted and filtered on the
// server, and a mutation that changes an order. GraphQL Yoga, on Node.js.
// node server.js (http://localhost:4000/graphql, or the port in PORT)
import { createServer } from 'node:http';
import { createSchema, createYoga } from 'graphql-yoga';
import { GraphQLError } from 'graphql';
const typeDefs = /* GraphQL */ `
enum OrderField { id customer product quantity price orderDate status }
enum Condition { CONTAINS EQUAL NOT_EQUAL GREATER_THAN LESS_THAN GREATER_THAN_OR_EQUAL LESS_THAN_OR_EQUAL }
enum Status { New Shipped Delivered Cancelled }
type Order {
id: ID!
customer: String!
product: String!
quantity: Int!
price: Float!
orderDate: String!
status: Status!
}
type OrderPage {
rows: [Order!]!
total: Int!
}
input OrderFilter {
field: OrderField!
condition: Condition!
value: String!
}
input OrderSort {
field: OrderField!
descending: Boolean = false
}
type Query {
orders(offset: Int = 0, limit: Int = 20, sort: OrderSort, filters: [OrderFilter!] = []): OrderPage!
}
type Mutation {
updateOrder(id: ID!, quantity: Int, status: Status): Order!
}
`;
// 10,000 orders in memory, to keep the example self-contained; a real API asks its database.
const customers = ['Alfreds Futterkiste', 'Ana Trujillo', 'Antonio Moreno', 'Around the Horn', 'Berglunds snabbköp', 'Blauer See Delikatessen', 'Bólido Comidas', 'Ernst Handel'];
const products = ['Chai', 'Chang', 'Aniseed Syrup', 'Tofu', 'Konbu', 'Pavlova', 'Ikura', 'Queso Cabrales', 'Gnocchi', 'Mozzarella'];
const statuses = ['New', 'Shipped', 'Delivered', 'Cancelled'];
const today = new Date();
const orders = Array.from({ length: 10000 }, (_, k) => {
const i = k + 1;
const date = new Date(today.getFullYear(), today.getMonth(), today.getDate() - (i % 365));
return {
id: String(i),
customer: customers[i % 8],
product: products[(i * 7) % 10],
quantity: 1 + (i * 13) % 50,
price: Math.round(500 + (i * 37) % 9500) / 100,
orderDate: `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`,
status: statuses[(i * 3) % 4]
};
});
const numeric = new Set(['quantity', 'price']);
const value = (order, field) => (field === 'id' ? Number(order.id) : order[field]);
function matches(order, { field, condition, value: text }) {
const v = value(order, field);
const want = numeric.has(field) || field === 'id' ? Number(text) : text;
if (typeof want === 'number' && Number.isNaN(want)) return false;
switch (condition) {
case 'CONTAINS': return String(v).toLowerCase().includes(String(want).toLowerCase());
case 'EQUAL': return typeof v === 'string' ? v.toLowerCase() === String(want).toLowerCase() : v === want;
case 'NOT_EQUAL': return typeof v === 'string' ? v.toLowerCase() !== String(want).toLowerCase() : v !== want;
case 'GREATER_THAN': return v > want;
case 'LESS_THAN': return v < want;
case 'GREATER_THAN_OR_EQUAL': return v >= want;
case 'LESS_THAN_OR_EQUAL': return v <= want;
}
return false;
}
// (GraphQLError: Yoga shows its message to the client; other errors become "Unexpected error.")
const resolvers = {
Query: {
orders(_, { offset, limit, sort, filters }) {
let rows = orders.filter((o) => filters.every((f) => matches(o, f)));
if (sort) {
const dir = sort.descending ? -1 : 1;
rows = [...rows].sort((a, b) => {
const x = value(a, sort.field), y = value(b, sort.field);
return (x < y ? -1 : x > y ? 1 : 0) * dir;
});
}
const size = Math.min(Math.max(limit, 1), 200);
return { rows: rows.slice(Math.max(offset, 0), Math.max(offset, 0) + size), total: rows.length };
}
},
Mutation: {
updateOrder(_, { id, quantity, status }) {
const order = orders.find((o) => o.id === id);
if (!order) throw new GraphQLError(`No order ${id}`);
if (quantity != null) {
if (!Number.isInteger(quantity) || quantity < 1) throw new GraphQLError('The quantity must be a whole number above 0');
order.quantity = quantity;
}
if (status != null) order.status = status;
return order;
}
}
};
const yoga = createYoga({ schema: createSchema({ typeDefs, resolvers }) });
const port = Number(process.env.PORT) || 4000;
createServer(yoga).listen(port, () => console.log(`GraphQL API on http://localhost:${port}/graphql`));
The enums do the checking: a sort or filter on a field the schema does not name, or a condition it does not have, is refused before a resolver runs. The data is generated in memory to keep the example self-contained; a real API asks its database in the resolvers. Errors meant for the user are thrown as GraphQLError, which Yoga passes on; any other error reaches the client as Unexpected error., so a server's internals do not leak. Yoga answers the browser's cross-origin requests, so the app on Vite's port can call the API on port 4000. (To call it by a relative URL instead, forward /graphql with Vite's proxy, as Vue Server-Side Paging does for /api.)
A GraphQL request is a POST with the query and its variables as JSON. The answer has data, and errors when something failed, with the same HTTP status in both cases. This function returns the data, typed by the caller, or throws the first error:
// A GraphQL request: the query and its variables in, the data or the first error out.
async function graphql<T>(query: string, variables: object): Promise<T> {
const response = await fetch(GRAPHQL_URL, {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ query, variables })
});
const { data, errors } = await response.json();
if (errors?.length) throw new Error(errors[0].message);
return data;
}
The query asks for the fields the grid shows, and the mutation for the fields it changes:
const ORDERS = /* GraphQL */ `
query Orders($offset: Int!, $limit: Int!, $sort: OrderSort, $filters: [OrderFilter!]) {
orders(offset: $offset, limit: $limit, sort: $sort, filters: $filters) {
total
rows { id customer product quantity price orderDate status }
}
}`;
const UPDATE_ORDER = /* GraphQL */ `
mutation UpdateOrder($id: ID!, $quantity: Int, $status: Status) {
updateOrder(id: $id, quantity: $quantity, status: $status) { id quantity status }
}`;
The grid runs in virtual mode, as in Vue Server-Side Paging, and the data adapter gets a loadServerData function instead of a URL. It receives the grid's page, sort and filters; variables turns them into the query's arguments, keeping only the fields and conditions the schema has:
// The grid's state as the query's variables
function variables(params: GridState) {
const filters = [];
for (let i = 0; i < Number(params.filterscount || 0); i++) {
const field = String(params['filterdatafield' + i]), condition = String(params['filtercondition' + i]);
if (fieldNames.has(field) && conditions.has(condition)) {
filters.push({ field, condition, value: String(params['filtervalue' + i]) });
}
}
const sort = params.sortdatafield && fieldNames.has(params.sortdatafield) && params.sortorder
? { field: params.sortdatafield, descending: params.sortorder === 'desc' }
: null;
return { offset: params.pagenum * params.pagesize, limit: params.pagesize, sort, filters };
}
// One page of orders for the grid's state
async function loadOrders(params: GridState): Promise<OrdersPage> {
const { orders } = await graphql<{ orders: { total: number; rows: Order[] } }>(ORDERS, variables(params));
return { records: orders.rows, totalrecords: orders.total };
}
The adapter is a plain constant of the component, not a ref: Vue need not track it, and it reaches the grid through the template ref grid. A failed request leaves the grid empty and shows the API's message in status, above the grid:
const grid = ref<GridMethods | null>(null);
// The message above the grid
const status = ref('');
// set while the page itself changes a cell (a rollback): not an edit to save
let applying = false;
// One source for the grid's life. The adapter calls loadServerData instead of requesting
// the url (it needs one, but nothing is fetched from it).
const adapter: { totalrecords: number } = new jqx.dataAdapter({
datatype: 'json',
id: 'id',
datafields,
url: GRAPHQL_URL,
totalrecords: 0,
// Sorting and filtering happen on the server: ask again.
sort: () => grid.value?.updatebounddata('sort'),
filter: () => grid.value?.updatebounddata('filter')
}, {
// (A plain function: versions before 27.1.0 ignore an async one.)
loadServerData: (params: GridState, _settings: unknown, callback: (page: OrdersPage) => void) => {
loadOrders(params).then((page) => {
status.value = '';
return page;
}, (error: Error): OrdersPage => {
status.value = `Could not load the orders: ${error.message}`;
return { records: [], totalrecords: 0 };
}).then((page) => {
// (the grid is gone if it was unmounted while the page was loading)
if (!grid.value) return;
// (versions before 27.1.0 keep the previous total when the new one is 0: set it here)
adapter.totalrecords = page.totalrecords;
callback(page);
});
}
});
loadServerData is a plain function that calls the async loadOrders, and it sets adapter.totalrecords itself. Both are for versions before 27.1.0, which ignore an async function there and keep the previous total when a filter matches nothing; they do no harm in 27.1.0. The check of grid.value drops an answer that comes after the component was unmounted, when Vue has set the template ref to null.
Every prop of JqxGrid is a constant of the script. This matters because the Grid component applies its props to the grid again when it re-renders (jqwidgets-scripts 27.1.0 the ones whose value changed, earlier versions all of them), and applying source again binds it again: with constant props, a new message re-renders this component but not the grid, which keeps its page, sort and filters.
<template>
<main style="padding: 16px">
<h1>Orders</h1>
<p id="status" role="status">{{ status }}</p>
<!-- Every prop is a constant: the grid component applies all its props again whenever
it re-renders, and for source that means binding again. -->
<div id="grid">
<JqxGrid
ref="grid"
width="100%"
:height="560"
theme="material-purple"
:source="adapter"
:columns="columns"
:virtualmode="true"
:rendergridrows="rendergridrows"
:pageable="true"
:pagesize="20"
:pagesizeoptions="pagesizeoptions"
:sortable="true"
:filterable="true"
:showfilterrow="true"
:editable="true"
selectionmode="singlecell"
@cellvaluechanged="onCellValueChanged"
/>
</div>
</main>
</template>
A changed cell becomes an updateOrder mutation with the order's id and the one changed field. If the API refuses it, the cell gets its old value back and the app shows the API's message. The applying flag keeps that rollback from being sent as an edit of its own:
// An edit is sent as a mutation; if the API refuses it, the cell gets its old value back.
async function saveEdit({ datafield, rowindex, oldvalue, newvalue }: CellValueChangedEvent['args']) {
const row = grid.value!.getrowdata(rowindex);
try {
await graphql(UPDATE_ORDER, { id: row.id, [datafield]: newvalue });
status.value = `Order ${row.id} saved.`;
} catch (error) {
status.value = `Order ${row.id} was not saved: ${(error as Error).message}`;
applying = true;
grid.value?.setcellvalue(rowindex, datafield, oldvalue);
applying = false;
}
}
function onCellValueChanged(event: CellValueChangedEvent) {
if (!applying) saveEdit(event.args);
}
Replace src/App.vue:
<script setup lang="ts">
import { ref } from 'vue';
import JqxGrid from 'jqwidgets-scripts/jqwidgets-vue3/vue_jqxgrid.vue';
// Defined globally by the jQWidgets core, which the Grid component imports.
declare const jqx: any;
// The GraphQL endpoint (the server of step 1)
const GRAPHQL_URL = 'http://localhost:4000/graphql';
interface Order {
id: string;
customer: string;
product: string;
quantity: number;
price: number;
orderDate: string;
status: string;
}
// A GraphQL request: the query and its variables in, the data or the first error out.
async function graphql<T>(query: string, variables: object): Promise<T> {
const response = await fetch(GRAPHQL_URL, {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ query, variables })
});
const { data, errors } = await response.json();
if (errors?.length) throw new Error(errors[0].message);
return data;
}
const ORDERS = /* GraphQL */ `
query Orders($offset: Int!, $limit: Int!, $sort: OrderSort, $filters: [OrderFilter!]) {
orders(offset: $offset, limit: $limit, sort: $sort, filters: $filters) {
total
rows { id customer product quantity price orderDate status }
}
}`;
const UPDATE_ORDER = /* GraphQL */ `
mutation UpdateOrder($id: ID!, $quantity: Int, $status: Status) {
updateOrder(id: $id, quantity: $quantity, status: $status) { id quantity status }
}`;
// The grid's state, as loadServerData receives it: pagenum, pagesize, sortdatafield, sortorder,
// filterscount and filterdatafield0, filtercondition0, filtervalue0 ...
interface GridState {
pagenum: number;
pagesize: number;
sortdatafield?: string;
sortorder?: string;
filterscount?: number;
[filter: string]: unknown;
}
interface OrdersPage {
records: Order[];
totalrecords: number;
}
// A grid event carries its details in event.args.
interface CellValueChangedEvent {
args: { rowindex: number; datafield: string; oldvalue: unknown; newvalue: unknown };
}
// The grid methods this component calls.
interface GridMethods {
updatebounddata: (type?: string) => void;
getrowdata: (rowindex: number) => Order;
setcellvalue: (rowindex: number, datafield: string, value: unknown) => void;
}
const datafields = [
{ name: 'id', type: 'string' },
{ name: 'customer', type: 'string' },
{ name: 'product', type: 'string' },
{ name: 'quantity', type: 'number' },
{ name: 'price', type: 'number' },
{ name: 'orderDate', type: 'date', format: 'yyyy-MM-dd' },
{ name: 'status', type: 'string' }
];
const fieldNames = new Set(datafields.map((f) => f.name));
// the grid's filter conditions that the API's Condition enum has
const conditions = new Set(['CONTAINS', 'EQUAL', 'NOT_EQUAL', 'GREATER_THAN', 'LESS_THAN', 'GREATER_THAN_OR_EQUAL', 'LESS_THAN_OR_EQUAL']);
// The grid's state as the query's variables
function variables(params: GridState) {
const filters = [];
for (let i = 0; i < Number(params.filterscount || 0); i++) {
const field = String(params['filterdatafield' + i]), condition = String(params['filtercondition' + i]);
if (fieldNames.has(field) && conditions.has(condition)) {
filters.push({ field, condition, value: String(params['filtervalue' + i]) });
}
}
const sort = params.sortdatafield && fieldNames.has(params.sortdatafield) && params.sortorder
? { field: params.sortdatafield, descending: params.sortorder === 'desc' }
: null;
return { offset: params.pagenum * params.pagesize, limit: params.pagesize, sort, filters };
}
// One page of orders for the grid's state
async function loadOrders(params: GridState): Promise<OrdersPage> {
const { orders } = await graphql<{ orders: { total: number; rows: Order[] } }>(ORDERS, variables(params));
return { records: orders.rows, totalrecords: orders.total };
}
const grid = ref<GridMethods | null>(null);
// The message above the grid
const status = ref('');
// set while the page itself changes a cell (a rollback): not an edit to save
let applying = false;
// One source for the grid's life. The adapter calls loadServerData instead of requesting
// the url (it needs one, but nothing is fetched from it).
const adapter: { totalrecords: number } = new jqx.dataAdapter({
datatype: 'json',
id: 'id',
datafields,
url: GRAPHQL_URL,
totalrecords: 0,
// Sorting and filtering happen on the server: ask again.
sort: () => grid.value?.updatebounddata('sort'),
filter: () => grid.value?.updatebounddata('filter')
}, {
// (A plain function: versions before 27.1.0 ignore an async one.)
loadServerData: (params: GridState, _settings: unknown, callback: (page: OrdersPage) => void) => {
loadOrders(params).then((page) => {
status.value = '';
return page;
}, (error: Error): OrdersPage => {
status.value = `Could not load the orders: ${error.message}`;
return { records: [], totalrecords: 0 };
}).then((page) => {
// (the grid is gone if it was unmounted while the page was loading)
if (!grid.value) return;
// (versions before 27.1.0 keep the previous total when the new one is 0: set it here)
adapter.totalrecords = page.totalrecords;
callback(page);
});
}
});
const statuses = ['New', 'Shipped', 'Delivered', 'Cancelled'];
const columns = [
{ text: 'Order', datafield: 'id', width: 70, filterable: false, editable: false },
{ text: 'Customer', datafield: 'customer', width: 170, editable: false },
{ text: 'Product', datafield: 'product', width: 110, editable: false },
{
text: 'Quantity', datafield: 'quantity', width: 90, cellsalign: 'right', align: 'right', filtertype: 'number',
columntype: 'numberinput',
createeditor: (_row: number, _value: unknown, editor: any) => editor.jqxNumberInput({ decimalDigits: 0, min: 1, spinButtons: true }),
validation: (_cell: unknown, value: unknown) => (Number.isInteger(value) && Number(value) > 0) || { result: false, message: 'A whole number above 0' }
},
{ text: 'Price', datafield: 'price', width: 90, cellsalign: 'right', align: 'right', cellsformat: 'c2', filtertype: 'number', editable: false },
{ text: 'Date', datafield: 'orderDate', width: 110, cellsformat: 'yyyy-MM-dd', filtertype: 'range', editable: false },
{
text: 'Status', datafield: 'status', filtertype: 'list', filteritems: statuses,
columntype: 'dropdownlist',
createeditor: (_row: number, _value: unknown, editor: any) => editor.jqxDropDownList({ source: statuses, autoDropDownHeight: true })
}
];
// With virtualmode, the grid shows the rows loadServerData returned for the current page.
const rendergridrows = (params: { data: unknown[] }) => params.data;
const pagesizeoptions = ['20', '50', '100'];
// An edit is sent as a mutation; if the API refuses it, the cell gets its old value back.
async function saveEdit({ datafield, rowindex, oldvalue, newvalue }: CellValueChangedEvent['args']) {
const row = grid.value!.getrowdata(rowindex);
try {
await graphql(UPDATE_ORDER, { id: row.id, [datafield]: newvalue });
status.value = `Order ${row.id} saved.`;
} catch (error) {
status.value = `Order ${row.id} was not saved: ${(error as Error).message}`;
applying = true;
grid.value?.setcellvalue(rowindex, datafield, oldvalue);
applying = false;
}
}
function onCellValueChanged(event: CellValueChangedEvent) {
if (!applying) saveEdit(event.args);
}
</script>
<template>
<main style="padding: 16px">
<h1>Orders</h1>
<p id="status" role="status">{{ status }}</p>
<!-- Every prop is a constant: the grid component applies all its props again whenever
it re-renders, and for source that means binding again. -->
<div id="grid">
<JqxGrid
ref="grid"
width="100%"
:height="560"
theme="material-purple"
:source="adapter"
:columns="columns"
:virtualmode="true"
:rendergridrows="rendergridrows"
:pageable="true"
:pagesize="20"
:pagesizeoptions="pagesizeoptions"
:sortable="true"
:filterable="true"
:showfilterrow="true"
:editable="true"
selectionmode="singlecell"
@cellvaluechanged="onCellValueChanged"
/>
</div>
</main>
</template>
Start the API with node server.js, run npm run dev and open the address it prints. The pager reads 1-20 of 10000. Sort by Quantity, type ernst in the Customer filter (1-20 of 1250), and pick Shipped in the Status filter. Change a status: the network panel shows one updateOrder mutation. To try the API on its own, open http://localhost:4000/graphql: Yoga serves GraphiQL there.