Vue UI Components Documentation
Cloud Firestore, the database of Firebase, keeps documents in collections and tells a listening app about every change. This tutorial shows the two ways to put a collection in a jqxGrid in a Vue 3 app: a live grid that holds the latest orders and changes with the database, and a grid that reads a large collection a page at a time with query cursors. Edits are written back to the documents, and the database's security rules decide what is accepted.

You need a Firebase project with Cloud Firestore (console.firebase.google.com), or the Firestore emulator on your computer: npx firebase-tools emulators:start --only firestore --project demo-jqwidgets (it needs Java 21). The examples use the emulator and a collection orders with fields customer, product, quantity, price, orderDate (a timestamp) and status. 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. Add the Firebase SDK:
npm install firebase
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).
The app and the database go in a module of their own, src/firebase.ts. A module runs once, when it is first imported, so every component that imports db shares one database; code in <script setup> runs again for each instance of a component, and initializeApp may run only once. Your app's configuration is under Project settings > General > Your apps in the console; with the emulator, a project id starting with demo- is enough.
import { initializeApp } from 'firebase/app';
import { getFirestore, connectFirestoreEmulator } from 'firebase/firestore';
// Your web app's configuration: Project settings > General > Your apps in the Firebase
// console. (A project id that starts with "demo-" works with the emulator only.)
const firebaseConfig = {
projectId: 'demo-jqwidgets'
// apiKey, authDomain, appId ... for a real project
};
const app = initializeApp(firebaseConfig);
// One database for the whole app, created when this module is first imported.
export const db = getFirestore(app);
// The local emulator (firebase emulators:start); leave this line out for your project.
connectFirestoreEmulator(db, '127.0.0.1', 8080);
The SDK's functions are imported one by one, so the build only takes the parts of Firestore the app uses.
The grid is bound to a local array, so it sorts, filters and pages in the browser. toRow turns a document into a row: its id, its fields, and the Firestore Timestamp as a JavaScript Date, which the date column formats and filters.
// A document as a grid row: its id, its fields, and the Timestamp as a Date
const toRow = (snapshot: QueryDocumentSnapshot): Order => {
const data = snapshot.data();
return { id: snapshot.id, ...data, orderDate: data.orderDate.toDate() } as Order;
};
onSnapshot listens to a query: the latest 500 orders. Its first answer fills the grid; each later one carries only the documents that were added, changed or removed, and the grid applies them by document id with addrow, updaterow and deleterow. When a new order arrives, the oldest of the 500 leaves the query and its row goes. The listener starts in onMounted, when the grid exists (a child component is mounted before its parent's onMounted runs), and the function onSnapshot returns, which stops it, is called in onUnmounted:
// The latest 500 orders, live: the first snapshot fills the grid, each later one brings
// only what changed. Edits, by this page or anyone else, arrive the same way.
let unsubscribe = () => {};
onMounted(() => {
let loaded = false;
const latest = query(collection(db, 'orders'), orderBy('orderDate', 'desc'), limit(500));
unsubscribe = onSnapshot(latest, (snapshot) => {
const g = grid.value;
if (!g) return;
if (!loaded) {
source.localdata = snapshot.docs.map(toRow);
g.updatebounddata();
loaded = true;
return;
}
applying = true;
for (const change of snapshot.docChanges()) {
if (change.type === 'added') g.addrow(change.doc.id, toRow(change.doc), 'first');
if (change.type === 'modified') g.updaterow(change.doc.id, toRow(change.doc));
if (change.type === 'removed') g.deleterow(change.doc.id);
}
applying = false;
}, (error) => {
status.value = `Could not load the orders: ${error.message}`;
});
});
// Stop listening when the grid goes.
onUnmounted(() => unsubscribe());
The changes go to the grid through its methods, not through a reactive array: a new array as the source would bind all 500 rows again for each change. The loaded flag belongs to one mount, so a component mounted again fills the grid from its own first snapshot.
The source uses the document id as the row id (id: 'id'), which is what lets each change find its row. It is a plain constant of the component, made once, and the first snapshot puts the rows into its localdata:
// One source for the grid's life: a local array, which the first snapshot fills. The grid
// sorts, filters and pages it in the browser.
const source = {
datatype: 'array',
localdata: [] as Order[],
id: 'id',
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' },
{ name: 'status', type: 'string' }
]
};
const adapter = new jqx.dataAdapter(source);
Every prop of JqxGrid is such a constant. 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"
:pageable="true"
:pagesize="20"
:sortable="true"
:filterable="true"
:showfilterrow="true"
:editable="true"
selectionmode="singlecell"
@cellvaluechanged="onCellValueChanged"
/>
</div>
</main>
</template>
A changed cell is written to its document with updateDoc. Firestore shows the new value at once, before the server answers. If the security rules refuse the write, Firestore takes it back, and the snapshot listener of step 2 puts the old value into the cell; the app only reports why. The applying flag keeps the listener's own changes from being written back.
// An edit is written to its document. Firestore shows it at once, and takes it back if
// the security rules refuse it (the snapshot listener above brings the old value).
async function saveEdit({ datafield, rowindex, newvalue }: CellValueChangedEvent['args']) {
const row = grid.value!.getrowdata(rowindex);
try {
await updateDoc(doc(db, 'orders', row.id), { [datafield]: newvalue });
status.value = 'Saved.';
} catch (error) {
status.value = `Not saved: ${(error as Error).message}`;
}
}
function onCellValueChanged(event: CellValueChangedEvent) {
if (!applying) saveEdit(event.args);
}
The rules are the real protection, since anyone can change the code that runs in a browser. These allow reading orders and changing only their quantity (a whole number above 0) and status (one of four values):
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
// Anyone may read orders and change their quantity and status (the tutorial's grid);
// a real app checks request.auth here.
match /orders/{orderId} {
allow read: if true;
allow update: if request.resource.data.diff(resource.data).affectedKeys().hasOnly(['quantity', 'status'])
&& request.resource.data.quantity is int && request.resource.data.quantity > 0
&& request.resource.data.status in ['New', 'Shipped', 'Delivered', 'Cancelled'];
allow create: if request.resource.data.keys().hasAll(['customer', 'product', 'quantity', 'price', 'orderDate', 'status'])
&& request.resource.data.orderDate is timestamp;
allow delete: if true;
}
}
}
Deploy them with firebase deploy --only firestore:rules; the emulator reads them from firestore.rules next to firebase.json. A quantity of 2.5 entered through the grid's API is refused by the rules, and the cell shows the old quantity again.
A live query that holds the whole collection is right for hundreds or a few thousand documents. For more, read one page at a time. Firestore has no offsets: a page starts after a document, the last one of the page before it. The grid runs in virtual mode with loadServerData, and the page reader keeps the last document of each page it has read, so the next page is one query and a jump ahead reads the pages in between once.
// Firestore pages with cursors, not offsets: a page starts after the last document of
// the page before it. lastDocs[n] is the last document of page n, for the current sort
// and page size; going to a page further on reads the pages in between once. The
// count is an aggregation query: it is billed as one read per 1,000 documents.
function cursorPages() {
let lastDocs: QueryDocumentSnapshot[] = [];
let order = '';
let total = 0;
return async function loadPage(params: GridState): Promise<OrdersPage> {
const field = params.sortdatafield && sortable.has(params.sortdatafield) && params.sortorder ? params.sortdatafield : 'orderDate';
const direction = params.sortorder === 'asc' ? 'asc' : 'desc';
if (order !== `${field} ${direction} ${params.pagesize}`) {
order = `${field} ${direction} ${params.pagesize}`;
lastDocs = [];
total = (await getCountFromServer(orders)).data().count;
}
const sorted = query(orders, orderBy(field, direction));
let page: QuerySnapshot | null = null;
for (let n = Math.min(lastDocs.length, params.pagenum); n <= params.pagenum; n++) {
const after = n > 0 ? [startAfter(lastDocs[n - 1])] : [];
page = await getDocs(query(sorted, ...after, limit(params.pagesize)));
if (page.docs.length) lastDocs[n] = page.docs[page.docs.length - 1];
}
const records = page!.docs.map((d) => ({ id: d.id, ...d.data(), orderDate: d.data().orderDate.toDate() }));
return { records, totalrecords: total };
};
}
cursorPages returns a reader with its own cursors. The component makes one, with its source; the source and adapter are those of Vue Server-Side Paging, with loadServerData a plain function, as versions before 27.1.0 need. Sorting is done by Firestore, so a new sort starts a new list of cursors:
// One source, and one list of cursors, for the grid's life.
const loadPage = cursorPages();
const adapter: { totalrecords: number } = new jqx.dataAdapter({
// (json: the adapter asks for data through loadServerData, which an array source never does)
datatype: 'json',
id: 'id',
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' },
{ name: 'status', type: 'string' }
],
// The adapter needs a url to ask for data; loadServerData below does the asking.
url: 'orders',
totalrecords: 0,
// Sorting happens in Firestore: ask again.
sort: () => grid.value?.updatebounddata('sort')
}, {
loadServerData: (params: GridState, _settings: unknown, callback: (page: OrdersPage) => void) => {
loadPage(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;
adapter.totalrecords = page.totalrecords;
callback(page);
});
}
});
Firestore sorts by one field here without extra setup. Sorting by one field and filtering by another needs a composite index: Firestore's error message has a link that creates it. getCountFromServer counts without reading the documents; it is read again only when the sort or page size changes.
src/firebase.ts is the module of step 1. The live grid, as src/App.vue:
<script setup lang="ts">
import { onMounted, onUnmounted, ref } from 'vue';
import { collection, query, orderBy, limit, onSnapshot, doc, updateDoc, type QueryDocumentSnapshot } from 'firebase/firestore';
import JqxGrid from 'jqwidgets-scripts/jqwidgets-vue3/vue_jqxgrid.vue';
import { db } from './firebase';
// Defined globally by the jQWidgets core, which the Grid component imports.
declare const jqx: any;
interface Order {
id: string;
customer: string;
product: string;
quantity: number;
price: number;
orderDate: Date;
status: string;
}
// A grid event carries its details in event.args.
interface CellValueChangedEvent {
args: { rowindex: number; datafield: string; newvalue: unknown };
}
// The grid methods this component calls.
interface GridMethods {
updatebounddata: () => void;
getrowdata: (rowindex: number) => Order;
addrow: (id: string, row: Order, position: 'first' | 'last') => void;
updaterow: (id: string, row: Order) => void;
deleterow: (id: string) => void;
}
// A document as a grid row: its id, its fields, and the Timestamp as a Date
const toRow = (snapshot: QueryDocumentSnapshot): Order => {
const data = snapshot.data();
return { id: snapshot.id, ...data, orderDate: data.orderDate.toDate() } as Order;
};
const grid = ref<GridMethods | null>(null);
// The message above the grid
const status = ref('');
// set while the snapshot listener changes the rows: not edits to save
let applying = false;
// One source for the grid's life: a local array, which the first snapshot fills. The grid
// sorts, filters and pages it in the browser.
const source = {
datatype: 'array',
localdata: [] as Order[],
id: 'id',
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' },
{ name: 'status', type: 'string' }
]
};
const adapter = new jqx.dataAdapter(source);
const statuses = ['New', 'Shipped', 'Delivered', 'Cancelled'];
const columns = [
{ text: 'Customer', datafield: 'customer', width: 180, editable: false },
{ text: 'Product', datafield: 'product', width: 120, 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 })
}
];
// The latest 500 orders, live: the first snapshot fills the grid, each later one brings
// only what changed. Edits, by this page or anyone else, arrive the same way.
let unsubscribe = () => {};
onMounted(() => {
let loaded = false;
const latest = query(collection(db, 'orders'), orderBy('orderDate', 'desc'), limit(500));
unsubscribe = onSnapshot(latest, (snapshot) => {
const g = grid.value;
if (!g) return;
if (!loaded) {
source.localdata = snapshot.docs.map(toRow);
g.updatebounddata();
loaded = true;
return;
}
applying = true;
for (const change of snapshot.docChanges()) {
if (change.type === 'added') g.addrow(change.doc.id, toRow(change.doc), 'first');
if (change.type === 'modified') g.updaterow(change.doc.id, toRow(change.doc));
if (change.type === 'removed') g.deleterow(change.doc.id);
}
applying = false;
}, (error) => {
status.value = `Could not load the orders: ${error.message}`;
});
});
// Stop listening when the grid goes.
onUnmounted(() => unsubscribe());
// An edit is written to its document. Firestore shows it at once, and takes it back if
// the security rules refuse it (the snapshot listener above brings the old value).
async function saveEdit({ datafield, rowindex, newvalue }: CellValueChangedEvent['args']) {
const row = grid.value!.getrowdata(rowindex);
try {
await updateDoc(doc(db, 'orders', row.id), { [datafield]: newvalue });
status.value = 'Saved.';
} catch (error) {
status.value = `Not saved: ${(error as Error).message}`;
}
}
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"
:pageable="true"
:pagesize="20"
:sortable="true"
:filterable="true"
:showfilterrow="true"
:editable="true"
selectionmode="singlecell"
@cellvaluechanged="onCellValueChanged"
/>
</div>
</main>
</template>
The paged grid:
<script setup lang="ts">
import { ref } from 'vue';
import {
collection, query, orderBy, limit, startAfter, getDocs, getCountFromServer,
type QueryDocumentSnapshot, type QuerySnapshot
} from 'firebase/firestore';
import JqxGrid from 'jqwidgets-scripts/jqwidgets-vue3/vue_jqxgrid.vue';
import { db } from './firebase';
// Defined globally by the jQWidgets core, which the Grid component imports.
declare const jqx: any;
const orders = collection(db, 'orders');
const sortable = new Set(['customer', 'product', 'quantity', 'price', 'orderDate']);
// The grid's state, as loadServerData receives it
interface GridState {
pagenum: number;
pagesize: number;
sortdatafield?: string;
sortorder?: string;
}
interface OrdersPage {
records: object[];
totalrecords: number;
}
// The grid methods this component calls.
interface GridMethods {
updatebounddata: (type?: string) => void;
}
// Firestore pages with cursors, not offsets: a page starts after the last document of
// the page before it. lastDocs[n] is the last document of page n, for the current sort
// and page size; going to a page further on reads the pages in between once. The
// count is an aggregation query: it is billed as one read per 1,000 documents.
function cursorPages() {
let lastDocs: QueryDocumentSnapshot[] = [];
let order = '';
let total = 0;
return async function loadPage(params: GridState): Promise<OrdersPage> {
const field = params.sortdatafield && sortable.has(params.sortdatafield) && params.sortorder ? params.sortdatafield : 'orderDate';
const direction = params.sortorder === 'asc' ? 'asc' : 'desc';
if (order !== `${field} ${direction} ${params.pagesize}`) {
order = `${field} ${direction} ${params.pagesize}`;
lastDocs = [];
total = (await getCountFromServer(orders)).data().count;
}
const sorted = query(orders, orderBy(field, direction));
let page: QuerySnapshot | null = null;
for (let n = Math.min(lastDocs.length, params.pagenum); n <= params.pagenum; n++) {
const after = n > 0 ? [startAfter(lastDocs[n - 1])] : [];
page = await getDocs(query(sorted, ...after, limit(params.pagesize)));
if (page.docs.length) lastDocs[n] = page.docs[page.docs.length - 1];
}
const records = page!.docs.map((d) => ({ id: d.id, ...d.data(), orderDate: d.data().orderDate.toDate() }));
return { records, totalrecords: total };
};
}
const grid = ref<GridMethods | null>(null);
// The message above the grid
const status = ref('');
// One source, and one list of cursors, for the grid's life.
const loadPage = cursorPages();
const adapter: { totalrecords: number } = new jqx.dataAdapter({
// (json: the adapter asks for data through loadServerData, which an array source never does)
datatype: 'json',
id: 'id',
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' },
{ name: 'status', type: 'string' }
],
// The adapter needs a url to ask for data; loadServerData below does the asking.
url: 'orders',
totalrecords: 0,
// Sorting happens in Firestore: ask again.
sort: () => grid.value?.updatebounddata('sort')
}, {
loadServerData: (params: GridState, _settings: unknown, callback: (page: OrdersPage) => void) => {
loadPage(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;
adapter.totalrecords = page.totalrecords;
callback(page);
});
}
});
const columns = [
{ text: 'Customer', datafield: 'customer', width: 180 },
{ text: 'Product', datafield: 'product', width: 120 },
{ text: 'Quantity', datafield: 'quantity', width: 90, cellsalign: 'right', align: 'right' },
{ text: 'Price', datafield: 'price', width: 90, cellsalign: 'right', align: 'right', cellsformat: 'c2' },
{ text: 'Date', datafield: 'orderDate', width: 110, cellsformat: 'yyyy-MM-dd' },
{ text: 'Status', datafield: 'status', sortable: false }
];
// With virtualmode, the grid shows the rows loadServerData returned for the current page.
const rendergridrows = (params: { data: unknown[] }) => params.data;
</script>
<template>
<main style="padding: 16px">
<h1>Orders</h1>
<p id="status" role="status">{{ status }}</p>
<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"
:sortable="true"
/>
</div>
</main>
</template>
Start the emulator and add some orders (the emulator's UI, or a short script with addDoc), then run npm run dev and open the address it prints. Change a document in the Firebase console or the emulator UI: its row changes in the grid. Add an order dated today: it appears at the top. In the paged grid, go to page 3, then click the Quantity header: Firestore sorts and the grid shows page 3 of the new order.