Vue UI Components Documentation
This tutorial builds a Vue Grid whose filters run in the database. When the user types in the filter row or picks values, the grid requests the data again with the filter conditions, and a Node.js API turns them into a parameterised WHERE clause.
The stack is Node 22 with Express 5 and mysql2/promise on the server, and Vue 3.5 with <script setup> and TypeScript, built with Vite, in the browser.
Create a Vue app with create-vue (answer Yes to TypeScript), add jQWidgets, and add the two server packages. The API lives in a server folder inside the same project.
npm create vue@latest my-app
cd my-app
npm install
npm install jqwidgets-scripts
npm install express mysql2
create-vue sets "type": "module" in package.json, so the server files can use import as well. The finished project looks like this:
my-app/
├── server/
│ ├── db.js # MySQL connection pool
│ ├── seed.js # creates and fills the orders table
│ └── server.js # Express API
├── src/
│ ├── App.vue # the grid
│ ├── jqwidgets-vue3.d.ts
│ └── main.ts
├── index.html
├── package.json
└── vite.config.ts
You need a MySQL 8 (or MariaDB) server on your machine. XAMPP, a Docker container or a local install all work. Create an empty database:
mysql -u root -p -e "CREATE DATABASE IF NOT EXISTS northwind CHARACTER SET utf8mb4"
Keep the connection settings in one module, server/db.js. It reads them from environment variables and falls back to a local root user, so no password is written into the code:
// server/db.js
import mysql from 'mysql2/promise';
// A pool reuses connections between requests.
export const pool = mysql.createPool({
host: process.env.DB_HOST ?? 'localhost',
user: process.env.DB_USER ?? 'root',
password: process.env.DB_PASSWORD ?? '',
database: process.env.DB_NAME ?? 'northwind',
connectionLimit: 10
});
With Node 22 you can keep these variables in a .env file and start scripts with node --env-file=.env. Add .env to .gitignore.
Create server/seed.js. It creates an orders table with a few Northwind shipping addresses:
// server/seed.js
import { pool } from './db.js';
const orders = [
['Vins et alcools Chevalier', '59 rue de l\'Abbaye', 'Reims', 'France'],
['Toms Spezialitäten', 'Luisenstr. 48', 'Münster', 'Germany'],
['Hanari Carnes', 'Rua do Paço, 67', 'Rio de Janeiro', 'Brazil'],
['Victuailles en stock', '2, rue du Commerce', 'Lyon', 'France'],
['Suprêmes délices', 'Boulevard Tirou, 255', 'Charleroi', 'Belgium'],
['Chop-suey Chinese', 'Hauptstr. 31', 'Bern', 'Switzerland'],
['Richter Supermarkt', 'Starenweg 5', 'Genève', 'Switzerland'],
['Wellington Importadora', 'Rua do Mercado, 12', 'Resende', 'Brazil'],
['Ernst Handel', 'Kirchgasse 6', 'Graz', 'Austria'],
['Centro comercial Moctezuma', 'Sierras de Granada 9993', 'México D.F.', 'Mexico'],
['Ottilies Käseladen', 'Mehrheimerstr. 369', 'Köln', 'Germany'],
['Que Delícia', 'Rua da Panificadora, 12', 'Rio de Janeiro', 'Brazil'],
['Rattlesnake Canyon Grocery', '2817 Milton Dr.', 'Albuquerque', 'USA'],
['Folk och fä HB', 'Åkergatan 24', 'Bräcke', 'Sweden'],
['Blondel père et fils', '24, place Kléber', 'Strasbourg', 'France'],
['Wartian Herkku', 'Torikatu 38', 'Oulu', 'Finland'],
['Frankenversand', 'Berliner Platz 43', 'München', 'Germany'],
['GROSELLA-Restaurante', '5ª Ave. Los Palos Grandes', 'Caracas', 'Venezuela'],
['White Clover Markets', '1029 - 12th Ave. S.', 'Seattle', 'USA'],
['Island Trading', 'Garden House Crowther Way', 'Cowes', 'UK']
];
await pool.query(`CREATE TABLE IF NOT EXISTS orders (
id INT AUTO_INCREMENT PRIMARY KEY,
ship_name VARCHAR(100) NOT NULL,
ship_address VARCHAR(100) NOT NULL,
ship_city VARCHAR(50) NOT NULL,
ship_country VARCHAR(50) NOT NULL
)`);
await pool.query('TRUNCATE TABLE orders');
// "VALUES ?" with an array of arrays inserts all rows in one statement.
await pool.query('INSERT INTO orders (ship_name, ship_address, ship_city, ship_country) VALUES ?', [orders]);
console.log(`Inserted ${orders.length} orders`);
await pool.end();
node server/seed.js
When the user filters, the grid sends filterscount and, for each filter i, filterdatafieldi, filterconditioni (such as CONTAINS or EQUAL), filtervaluei and filteroperatori (0 for AND, 1 for OR between two filters on the same column). Create server/server.js:
// server/server.js
import express from 'express';
import { pool } from './db.js';
const app = express();
const PORT = 3000;
// Grid data field -> table column. Only these columns can be filtered.
const FILTER_COLUMNS = new Map([
['ShipName', 'ship_name'],
['ShipAddress', 'ship_address'],
['ShipCity', 'ship_city'],
['ShipCountry', 'ship_country']
]);
// Escape % and _ so that they are matched literally inside LIKE patterns.
const like = (value) => value.replace(/[\\%_]/g, '\\$&');
// Grid condition -> SQL fragment and how to turn the filter value into the parameter.
const CONDITIONS = new Map([
['CONTAINS', ['LIKE ?', (v) => `%${like(v)}%`]],
['DOES_NOT_CONTAIN', ['NOT LIKE ?', (v) => `%${like(v)}%`]],
['STARTS_WITH', ['LIKE ?', (v) => `${like(v)}%`]],
['ENDS_WITH', ['LIKE ?', (v) => `%${like(v)}`]],
['EQUAL', ['= ?', (v) => v]],
['NOT_EQUAL', ['<> ?', (v) => v]],
['EMPTY', ["= ''", null]],
['NOT_EMPTY', ["<> ''", null]],
['NULL', ['IS NULL', null]],
['NOT_NULL', ['IS NOT NULL', null]]
]);
function buildWhere(query) {
const count = Math.min(20, Number.parseInt(query.filterscount, 10) || 0);
const groups = new Map();
for (let i = 0; i < count; i++) {
const column = FILTER_COLUMNS.get(query[`filterdatafield${i}`]);
// The table uses a case-insensitive collation, so *_CASE_SENSITIVE conditions are treated like the plain ones.
const condition = CONDITIONS.get(String(query[`filtercondition${i}`]).replace(/_CASE_SENSITIVE$/, ''));
if (!column || !condition) {
continue;
}
const [sql, toParam] = condition;
const value = String(query[`filtervalue${i}`] ?? '');
if (!groups.has(column)) {
groups.set(column, []);
}
groups.get(column).push({
sql: `${column} ${sql}`,
params: toParam ? [toParam(value)] : [],
operator: query[`filteroperator${i}`] === '1' ? 'OR' : 'AND'
});
}
// Filters on the same column are joined with their operator; different columns with AND.
const clauses = [];
const params = [];
for (const parts of groups.values()) {
let clause = '';
parts.forEach((part, index) => {
clause += index === 0 ? part.sql : ` ${parts[index - 1].operator} ${part.sql}`;
params.push(...part.params);
});
clauses.push(`(${clause})`);
}
return { where: clauses.length ? `WHERE ${clauses.join(' AND ')}` : '', params };
}
app.get('/api/orders', async (req, res) => {
const { where, params } = buildWhere(req.query);
const [rows] = await pool.query(
`SELECT id, ship_name AS ShipName, ship_address AS ShipAddress,
ship_city AS ShipCity, ship_country AS ShipCountry
FROM orders
${where}
ORDER BY id`,
params
);
res.json(rows);
});
// Express 5 passes errors from async handlers here.
app.use((err, req, res, next) => {
console.error(err);
res.status(500).json({ error: 'Could not read the data' });
});
app.listen(PORT, () => {
console.log(`API listening on http://localhost:${PORT}`);
});
Every value the user typed goes into the params array and reaches MySQL through a ? placeholder. Column names and conditions are looked up in FILTER_COLUMNS and CONDITIONS; unknown ones are skipped, so nothing from the request is pasted into the SQL text.
Start the server and try http://localhost:3000/api/orders?filterscount=1&filterdatafield0=ShipCountry&filtercondition0=EQUAL&filtervalue0=Brazil&filteroperator0=0:
node --watch server/server.js
The Vite dev server runs on port 5173 and the API on port 3000. A proxy in vite.config.ts forwards /api requests, so you do not need CORS headers:
import { fileURLToPath, URL } from 'node:url';
import { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue';
export default defineConfig({
plugins: [vue()],
resolve: {
alias: {
'@': fileURLToPath(new URL('./src', import.meta.url))
}
},
server: {
proxy: {
// During development, requests to /api/... go to the Express server.
'/api': 'http://localhost:3000'
}
}
});
Load the jQWidgets styles in src/main.ts:
import { createApp } from 'vue';
import 'jqwidgets-scripts/jqwidgets/styles/jqx.base.css';
import 'jqwidgets-scripts/jqwidgets/styles/jqx.material-purple.css';
import App from './App.vue';
createApp(App).mount('#app');
The Vue components are plain JavaScript files, so TypeScript's strict mode rejects importing them (TS7016: Could not find a declaration file). Declare them once in a new file, src/jqwidgets-vue3.d.ts:
// src/jqwidgets-vue3.d.ts
declare module 'jqwidgets-scripts/jqwidgets-vue3/*.vue' {
import type { DefineComponent } from 'vue';
const component: DefineComponent<Record<string, any>, Record<string, any>, any>;
export default component;
}
Replace src/App.vue. The filter callback of the source makes filtering server-side: the grid calls it instead of filtering locally, and updatebounddata('filter') sends a new request with the filter parameters. showfilterrow adds a row of filter inputs under the headers, and filtertype: 'checkedlist' gives the Country column a list of values to pick from.
<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 grid method this component calls.
interface GridMethods {
updatebounddata: (type?: string) => void;
}
const myGrid = ref<GridMethods | null>(null);
// A plain constant, not a ref: Vue does not need to track the adapter.
const dataAdapter = new jqx.dataAdapter({
datatype: 'json',
url: '/api/orders',
cache: false,
id: 'id',
datafields: [
{ name: 'ShipName', type: 'string' },
{ name: 'ShipAddress', type: 'string' },
{ name: 'ShipCity', type: 'string' },
{ name: 'ShipCountry', type: 'string' }
],
filter: () => {
// Reload the data; the request carries the current filters.
myGrid.value?.updatebounddata('filter');
}
});
const columns = [
{ text: 'Ship Name', datafield: 'ShipName', width: 240 },
{ text: 'Address', datafield: 'ShipAddress', width: 260 },
{ text: 'City', datafield: 'ShipCity', width: 150 },
{ text: 'Country', datafield: 'ShipCountry', filtertype: 'checkedlist' }
];
</script>
<template>
<JqxGrid
ref="myGrid"
theme="material-purple"
:width="800"
:height="450"
:source="dataAdapter"
:columns="columns"
:filterable="true"
:showfilterrow="true"
/>
</template>
Checking two countries in the list sends two EQUAL filters on ShipCountry joined with OR, which the server turns into (ship_country = ? OR ship_country = ?).
Keep the API running in one terminal and start Vite in a second one:
npm run dev
Open http://localhost:5173 and type rio in the City filter. The Network tab shows a request with filterscount=1, filterdatafield0=ShipCity and filtercondition0=CONTAINS, and the grid shows the two Rio de Janeiro orders.
Run npm run build and serve the dist folder from the same Express app, for example with app.use(express.static('dist')). Then /api and the page share one origin, and neither the proxy nor CORS headers are needed.
Related: server-side paging, server-side sorting, Grid filtering. See the Grid demos at jqwidgets.com/vue.