Vue UI Components Documentation
This tutorial builds a Vue Grid whose sorting is done by the database. Each time the user sorts a column, the grid requests the rows again with the sort column and direction, and a Node.js API returns them in that order. Sort on the server when the data is large or when the database collation must decide the order.
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 clicks a column header, the grid sends sortdatafield (the data field name, for example ShipCity) and sortorder (asc, desc, or empty when sorting is removed). 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 sorted.
const SORT_COLUMNS = new Map([
['ShipName', 'ship_name'],
['ShipAddress', 'ship_address'],
['ShipCity', 'ship_city'],
['ShipCountry', 'ship_country']
]);
app.get('/api/orders', async (req, res) => {
const column = SORT_COLUMNS.get(req.query.sortdatafield);
const direction = req.query.sortorder === 'desc' ? 'DESC' : 'ASC';
const orderBy = column ? `ORDER BY ${column} ${direction}, id` : 'ORDER BY id';
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
${orderBy}`
);
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}`);
});
Column names and ASC/DESC cannot be sent as ? placeholders, so the server never copies them from the request. It looks the field up in SORT_COLUMNS and ignores anything that is not listed, which keeps the query safe from SQL injection.
Start the server and try http://localhost:3000/api/orders?sortdatafield=ShipCity&sortorder=desc:
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 sort callback of the source makes sorting server-side: the grid calls it instead of sorting the rows it already has, and updatebounddata('sort') sends a new request that includes sortdatafield and sortorder. The callback reaches the grid through a template ref.
<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' }
],
sort: () => {
// Reload the data; the request carries the new sort column and order.
myGrid.value?.updatebounddata('sort');
}
});
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' }
];
</script>
<template>
<JqxGrid
ref="myGrid"
theme="material-purple"
:width="800"
:height="450"
:source="dataAdapter"
:columns="columns"
:sortable="true"
/>
</template>
Keep the API running in one terminal and start Vite in a second one:
npm run dev
Open http://localhost:5173 and click a column header. The Network tab shows a request such as /api/orders?sortdatafield=ShipCity&sortorder=asc. When the sort is removed, sortorder is empty and the server falls back to the original order.
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 filtering, Grid sorting. See the Grid demos at jqwidgets.com/vue.