Vue UI Components Documentation
Supabase gives every project a PostgreSQL database with a REST API, Row Level Security and live change events. This tutorial connects a jqxGrid in a Vue 3 app to a Supabase table with the official JavaScript client, supabase-js: the database pages, sorts and filters 10,000 orders, edits are saved as the user makes them, and changes made anywhere else appear in the grid while it is open.

You need a Supabase project: a free one at supabase.com/dashboard, or a local one with the Supabase CLI (supabase start). 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: the theme imported in src/main.ts and the components declared in src/jqwidgets-vue3.d.ts. Add supabase-js:
npm install @supabase/supabase-js
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).
Run this SQL in the dashboard's SQL editor (or as a migration). It creates an orders table with 10,000 sample rows, and says what the browser may do with it:
-- The orders table: 10,000 sample orders, and what the browser may do with them.
create table public.orders (
id bigint generated always as identity primary key,
customer text not null,
product text not null,
quantity integer not null check (quantity > 0),
price numeric(10, 2) not null check (price >= 0),
order_date date not null,
status text not null default 'New' check (status in ('New', 'Shipped', 'Delivered', 'Cancelled'))
);
-- 10,000 sample orders
insert into public.orders (customer, product, quantity, price, order_date, status)
select
(array['Alfreds Futterkiste', 'Ana Trujillo', 'Antonio Moreno', 'Around the Horn', 'Berglunds snabbköp',
'Blauer See Delikatessen', 'Bólido Comidas', 'Ernst Handel'])[1 + i % 8],
(array['Chai', 'Chang', 'Aniseed Syrup', 'Tofu', 'Konbu', 'Pavlova', 'Ikura', 'Queso Cabrales',
'Gnocchi', 'Mozzarella'])[1 + (i * 7) % 10],
1 + (i * 13) % 50,
round((5 + (i * 37) % 9500 / 100.0)::numeric, 2),
current_date - (i % 365),
(array['New', 'Shipped', 'Delivered', 'Cancelled'])[1 + (i * 3) % 4]
from generate_series(1, 10000) as i;
-- Row Level Security: the browser uses the anon key, so the table says what that key may do.
-- Here anyone may read orders and change their quantity and status; a real app checks the
-- signed-in user (auth.uid()) in these policies.
alter table public.orders enable row level security;
create policy "Orders are readable" on public.orders
for select to anon, authenticated using (true);
create policy "Orders can be updated" on public.orders
for update to anon, authenticated using (true) with check (true);
grant select on public.orders to anon, authenticated;
grant update (quantity, status) on public.orders to anon, authenticated;
-- Realtime: changes to the table are sent to subscribed browsers (the same as switching on
-- Realtime for the table in the dashboard).
alter publication supabase_realtime add table public.orders;
The browser connects with the project's anon key, which anyone can read in the app's code. What it may do is decided in the database: Row Level Security is switched on and two policies allow reading and updating, and the column grants allow changing only quantity and status. An update of the price is refused by the database, whatever the app sends. In a real app the policies check the signed-in user, for example using (auth.uid() = owner_id). The last line adds the table to Realtime, for step 5.
The client goes in a module of its own, src/supabase.ts. A module runs once, when it is first imported, so every component that imports supabase shares one client; code in <script setup> runs again for each instance of a component. The URL and the anon key are under Project Settings > API in the dashboard; supabase start prints them for a local project (the values below are the local ones).
import { createClient } from '@supabase/supabase-js';
// Your project's URL and anon key: Project Settings > API in the Supabase dashboard
// (these are the ones `supabase start` prints for the local stack).
const SUPABASE_URL = 'http://127.0.0.1:54321';
const SUPABASE_ANON_KEY = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZS1kZW1vIiwicm9sZSI6ImFub24iLCJleHAiOjE5ODM4MTI5OTZ9.CRXP1A7WOeoJeXxjNni43kdQwgnWNReilDMblYTn_I0';
// One client for the whole app, created when this module is first imported.
export const supabase = createClient(SUPABASE_URL, SUPABASE_ANON_KEY);
In your own app, keep them in a .env file as VITE_SUPABASE_URL and VITE_SUPABASE_ANON_KEY and read them with import.meta.env.VITE_SUPABASE_URL: Vite passes variables that start with VITE_ to the browser code. Never put the service role key there; it bypasses Row Level Security.
The grid runs in virtual mode, as in Vue Server-Side Paging: it asks for one page at a time. Instead of a URL, the data adapter gets a loadServerData function, which receives the grid's state (the page, the sort and the filters) and hands the rows back through a callback. Here it builds one supabase-js query:
range(from, to) asks for the rows of the page, and count: 'exact' for the number of rows that match, which the pager shows;order() sorts by the grid's sort column, or by id so that the pages are stable;selectOrders starts the query, and its type is the type of every step that adds a condition:
const selectOrders = () => supabase.from('orders').select('*', { count: 'exact' });
type OrdersQuery = ReturnType<typeof selectOrders>;
// A grid filter as a PostgREST condition. (In a LIKE pattern, % and _ are wildcards:
// the user's text is escaped so that they match themselves.)
function addFilter(query: OrdersQuery, column: string, condition: string, value: string): OrdersQuery {
if (!columnNames.has(column)) return query;
const like = String(value).replace(/[\\%_]/g, (c) => '\\' + c);
switch (condition) {
case 'CONTAINS': return query.ilike(column, `%${like}%`);
case 'DOES_NOT_CONTAIN': return query.not(column, 'ilike', `%${like}%`);
case 'STARTS_WITH': return query.ilike(column, `${like}%`);
case 'ENDS_WITH': return query.ilike(column, `%${like}`);
case 'EQUAL': return query.eq(column, value);
case 'NOT_EQUAL': return query.neq(column, value);
case 'GREATER_THAN': return query.gt(column, value);
case 'LESS_THAN': return query.lt(column, value);
case 'GREATER_THAN_OR_EQUAL': return query.gte(column, value);
case 'LESS_THAN_OR_EQUAL': return query.lte(column, value);
case 'NULL': return query.is(column, null);
case 'NOT_NULL': return query.not(column, 'is', null);
default: return query;
}
}
ilike matches without regard to case. In its pattern % and _ are wildcards, so the user's text has them escaped: a search for 50% finds the text 50%.
// One page of orders for the grid's state
async function loadOrders(params: GridState): Promise<OrdersPage> {
const from = params.pagenum * params.pagesize;
let query = selectOrders().range(from, from + params.pagesize - 1);
for (let i = 0; i < Number(params.filterscount || 0); i++) {
query = addFilter(query, String(params['filterdatafield' + i]), String(params['filtercondition' + i]), String(params['filtervalue' + i]));
}
const sortBy = params.sortdatafield && columnNames.has(params.sortdatafield) && params.sortorder ? params.sortdatafield : 'id';
query = query.order(sortBy, { ascending: params.sortorder !== 'desc' });
const { data, count, error } = await query;
if (error) throw new Error(error.message);
return { records: data, totalrecords: count ?? 0 };
}
The source names the fields and asks again when the user sorts or filters. The adapter calls loadServerData instead of requesting url (it needs one, but nothing is fetched from it). It 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. status is the message shown 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, a live update): 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: 'orders',
totalrecords: 0,
// Sorting and filtering happen in the database: 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);
});
}
});
Two details are for versions before 27.1.0 and do no harm in 27.1.0: loadServerData is a plain function that calls the async loadOrders (earlier versions ignore an async function there), and it sets adapter.totalrecords itself, because earlier versions keep the previous total when a filter matches no rows. The check of grid.value is for Vue: if the component is unmounted while a page is loading, Vue sets the template ref to null, and the answer is dropped.
The columns are those of the server-side tutorials, with editors for the two columns the database lets the user change:
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: 'order_date', 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 })
}
];
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>
When a cell changes, @cellvaluechanged sends an update of that one column. If the database refuses it, the cell gets its old value back and the app says why, in the words of the database: a quantity of 0 breaks the table's check, for example.
// An edit is saved to the database; if the database refuses it, the cell gets its old value back.
async function saveEdit({ datafield, rowindex, oldvalue, newvalue }: CellValueChangedEvent['args']) {
const row = grid.value!.getrowdata(rowindex);
const { error } = await supabase.from('orders').update({ [datafield]: newvalue }).eq('id', row.id);
if (error) {
status.value = `Order ${row.id} was not saved: ${error.message}`;
applying = true;
grid.value?.setcellvalue(rowindex, datafield, oldvalue);
applying = false;
} else {
status.value = `Order ${row.id} saved.`;
}
}
function onCellValueChanged(event: CellValueChangedEvent) {
if (!applying) saveEdit(event.args);
}
The applying flag keeps the grid's own changes from being saved again: the rollback above, and the live updates of the next step. It is a plain variable, not a ref, because nothing is drawn from it and setting it must not render anything.
A Realtime channel delivers each change to the table. When an order on the current page changes, in another tab, by another user or in the dashboard, its cells show the new values. The channel is subscribed when the component is mounted, and onUnmounted leaves it when the grid goes:
// Changes made elsewhere (another user, another tab, the dashboard) arrive through
// Realtime; an order on the current page shows its new values.
const channel = supabase
// (a topic of its own for each mount: a channel that is still being removed keeps its topic)
.channel(`orders-changes-${crypto.randomUUID()}`)
.on<Order>('postgres_changes', { event: 'UPDATE', schema: 'public', table: 'orders' }, ({ new: order }) => {
const g = grid.value;
if (!g) return;
const rows = g.getrows();
const index = rows.findIndex((r) => r.id === order.id);
if (index < 0) return;
applying = true;
for (const field of ['quantity', 'status'] as const) {
if (rows[index][field] !== order[field]) g.setcellvalue(index, field, order[field]);
}
applying = false;
});
onMounted(() => channel.subscribe());
// Leave the channel when the grid goes.
onUnmounted(() => supabase.removeChannel(channel));
supabase.channel() returns the channel of the same name if there is one, and removeChannel takes a moment to leave it. A component unmounted and mounted again at once (a route change and back, a v-if that flips) would get, with a fixed name, the channel that is being removed, and no channel would join. A name of its own for each mount avoids that.
Realtime checks the same Row Level Security policies, so a browser only receives the rows it may read. For a grid that should also show new and deleted rows, listen to event: '*' and ask for the page again with grid.value?.updatebounddata().
src/supabase.ts is the module of step 2. Replace src/App.vue:
<script setup lang="ts">
import { onMounted, onUnmounted, ref } from 'vue';
import JqxGrid from 'jqwidgets-scripts/jqwidgets-vue3/vue_jqxgrid.vue';
import { supabase } from './supabase';
// Defined globally by the jQWidgets core, which the Grid component imports.
declare const jqx: any;
interface Order {
id: number;
customer: string;
product: string;
quantity: number;
price: number;
order_date: string;
status: string;
}
// 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;
getrows: () => Order[];
getrowdata: (rowindex: number) => Order;
setcellvalue: (rowindex: number, datafield: string, value: unknown) => void;
}
const datafields = [
{ name: 'id', type: 'number' },
{ name: 'customer', type: 'string' },
{ name: 'product', type: 'string' },
{ name: 'quantity', type: 'number' },
{ name: 'price', type: 'number' },
{ name: 'order_date', type: 'date', format: 'yyyy-MM-dd' },
{ name: 'status', type: 'string' }
];
const columnNames = new Set(datafields.map((f) => f.name));
const selectOrders = () => supabase.from('orders').select('*', { count: 'exact' });
type OrdersQuery = ReturnType<typeof selectOrders>;
// A grid filter as a PostgREST condition. (In a LIKE pattern, % and _ are wildcards:
// the user's text is escaped so that they match themselves.)
function addFilter(query: OrdersQuery, column: string, condition: string, value: string): OrdersQuery {
if (!columnNames.has(column)) return query;
const like = String(value).replace(/[\\%_]/g, (c) => '\\' + c);
switch (condition) {
case 'CONTAINS': return query.ilike(column, `%${like}%`);
case 'DOES_NOT_CONTAIN': return query.not(column, 'ilike', `%${like}%`);
case 'STARTS_WITH': return query.ilike(column, `${like}%`);
case 'ENDS_WITH': return query.ilike(column, `%${like}`);
case 'EQUAL': return query.eq(column, value);
case 'NOT_EQUAL': return query.neq(column, value);
case 'GREATER_THAN': return query.gt(column, value);
case 'LESS_THAN': return query.lt(column, value);
case 'GREATER_THAN_OR_EQUAL': return query.gte(column, value);
case 'LESS_THAN_OR_EQUAL': return query.lte(column, value);
case 'NULL': return query.is(column, null);
case 'NOT_NULL': return query.not(column, 'is', null);
default: return query;
}
}
// One page of orders for the grid's state
async function loadOrders(params: GridState): Promise<OrdersPage> {
const from = params.pagenum * params.pagesize;
let query = selectOrders().range(from, from + params.pagesize - 1);
for (let i = 0; i < Number(params.filterscount || 0); i++) {
query = addFilter(query, String(params['filterdatafield' + i]), String(params['filtercondition' + i]), String(params['filtervalue' + i]));
}
const sortBy = params.sortdatafield && columnNames.has(params.sortdatafield) && params.sortorder ? params.sortdatafield : 'id';
query = query.order(sortBy, { ascending: params.sortorder !== 'desc' });
const { data, count, error } = await query;
if (error) throw new Error(error.message);
return { records: data, totalrecords: count ?? 0 };
}
const grid = ref<GridMethods | null>(null);
// The message above the grid
const status = ref('');
// set while the page itself changes a cell (a rollback, a live update): 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: 'orders',
totalrecords: 0,
// Sorting and filtering happen in the database: 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: 'order_date', 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 saved to the database; if the database refuses it, the cell gets its old value back.
async function saveEdit({ datafield, rowindex, oldvalue, newvalue }: CellValueChangedEvent['args']) {
const row = grid.value!.getrowdata(rowindex);
const { error } = await supabase.from('orders').update({ [datafield]: newvalue }).eq('id', row.id);
if (error) {
status.value = `Order ${row.id} was not saved: ${error.message}`;
applying = true;
grid.value?.setcellvalue(rowindex, datafield, oldvalue);
applying = false;
} else {
status.value = `Order ${row.id} saved.`;
}
}
function onCellValueChanged(event: CellValueChangedEvent) {
if (!applying) saveEdit(event.args);
}
// Changes made elsewhere (another user, another tab, the dashboard) arrive through
// Realtime; an order on the current page shows its new values.
const channel = supabase
// (a topic of its own for each mount: a channel that is still being removed keeps its topic)
.channel(`orders-changes-${crypto.randomUUID()}`)
.on<Order>('postgres_changes', { event: 'UPDATE', schema: 'public', table: 'orders' }, ({ new: order }) => {
const g = grid.value;
if (!g) return;
const rows = g.getrows();
const index = rows.findIndex((r) => r.id === order.id);
if (index < 0) return;
applying = true;
for (const field of ['quantity', 'status'] as const) {
if (rows[index][field] !== order[field]) g.setcellvalue(index, field, order[field]);
}
applying = false;
});
onMounted(() => channel.subscribe());
// Leave the channel when the grid goes.
onUnmounted(() => supabase.removeChannel(channel));
</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>
Run npm run dev and open the address it prints. The pager reads 1-20 of 10000. Click the Quantity header twice to sort from the largest order, and type ernst in the Customer filter: the pager reads 1-20 of 1250, still sorted. Type a name that no order has: the grid is empty and the pager reads 0-0 of 0. Double-click a status, pick Delivered, and see the row change in the Table Editor of the dashboard. Open the app in a second tab and change a quantity in the first: the second tab shows it a moment later.