To create a Vue.js application that counts clicks on links and stores the count along with the URL in an SQLite database, you need both a frontend (Vue.js) and a backend (Node.js with SQLite) because Vue.js runs in the browser and cannot directly write to a database.
Here’s a simple example:
Backend (Node.js + Express + SQLite)
- Initialize a Node.js project and install dependencies:
npm init -y
npm install express sqlite3 cors body-parser
- Create
server.js:
const express = require('express');
const sqlite3 = require('sqlite3').verbose();
const cors = require('cors');
const bodyParser = require('body-parser');
const app = express();
const PORT = 3000;
app.use(cors());
app.use(bodyParser.json());
// Initialize SQLite DB
const db = new sqlite3.Database('./clicks.db', (err) => {
if (err) {
console.error('Error opening database', err);
} else {
db.run(`CREATE TABLE IF NOT EXISTS clicks (
id INTEGER PRIMARY KEY AUTOINCREMENT,
url TEXT NOT NULL,
count INTEGER NOT NULL DEFAULT 0
)`);
}
});
// Endpoint to increment click count
app.post('/click', (req, res) => {
const { url } = req.body;
if (!url) {
return res.status(400).json({ error: 'URL is required' });
}
// Check if URL exists
db.get('SELECT * FROM clicks WHERE url = ?', [url], (err, row) => {
if (err) {
return res.status(500).json({ error: err.message });
}
if (row) {
// Update count
db.run('UPDATE clicks SET count = count + 1 WHERE url = ?', [url], function(err) {
if (err) {
return res.status(500).json({ error: err.message });
}
res.json({ url, count: row.count + 1 });
});
} else {
// Insert new row
db.run('INSERT INTO clicks (url, count) VALUES (?, 1)', [url], function(err) {
if (err) {
return res.status(500).json({ error: err.message });
}
res.json({ url, count: 1 });
});
}
});
});
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
});
Run the backend server:
node server.js
Frontend (Vue.js)
- Create a Vue component that sends click info to the backend:
<template>
<div>
<a
v-for="link in links"
:key="link.url"
:href="link.url"
@click.prevent="handleClick(link.url)"
target="_blank"
rel="noopener noreferrer"
>
{{ link.text }}
</a>
</div>
</template>
<script>
export default {
data() {
return {
links: [
{ url: 'https://vuejs.org', text: 'Vue.js' },
{ url: 'https://nodejs.org', text: 'Node.js' },
{ url: 'https://sqlite.org', text: 'SQLite' },
],
};
},
methods: {
async handleClick(url) {
try {
const response = await fetch('http://localhost:3000/click', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ url }),
});
const data = await response.json();
console.log(`Clicked ${data.url}, count: ${data.count}`);
// Optionally, navigate to the link after logging
window.open(url, '_blank');
} catch (error) {
console.error('Error logging click:', error);
}
},
},
};
</script>
How it works:
- When a user clicks a link, the Vue app sends a POST request to the backend with the URL.
- The backend increments the click count in the SQLite database.
- The frontend optionally opens the link in a new tab after logging the click.
If you want me to help you set this up with a full Vue CLI project or with Vue 3 Composition API, just ask!