Planning Vue.js App with Offline Capabilities
The user wants a Vue.js app that supports offline editing and synchronization using IndexedDB. To cover offline editing and sync, I need to include a Service Worker, an IndexedDB wrapper like idb, a sync queue, and basic conflict resolution.
Focusing on Vue 3 with the composition API and Vite, I should provide a minimal yet functional example. This will include project structure, main.js, App.vue, along with components for list/edit, db.js for IndexedDB, and syncService.js for synchronization. Additionally, I might mention libraries like Dexie and provide hypothetical API endpoints.Structuring Offline Sync App
I can't include emojis. The app needs offline editing and synchronization, so users can create or edit items stored in IndexedDB and sync them with the server once online. I'll design a simple queue for "pendingChanges" with a "dirty" flag or syncStatus property.
I'll provide a quick overview of the architecture and include snippets like package.json dependencies (including "idb"), src/db.js for interactions, src/api.js for REST API calls, and src/sync.js for synchronization logic. I'll also mention offline detection with window.addEventListener and service worker registration in main.js. Finally, I'll explain how to test offline functionality using dev tools.Designing "Offline Notes" App
Since my knowledge cutoff is in October 2024, I can mention recommended libraries like @vueuse/core, but I’ll keep it minimal. The user didn't specify which Vue version to use, but I’ll choose Vue 3 as it's modern. The app will be called "Offline Notes" with a data model including fields like id, title, content, updatedAt, and syncStatus (which could be 'synced', 'pending', or 'failed').
We’ll store all note records in IndexedDB. When a user edits, creates, or deletes a note, it will initially be marked as pending, whether offline or if a server call fails. I’ll implement an optimistic UI pattern by writing to IndexedDB first and then syncing with the server. To avoid concurrency issues, I need to consider cases with multiple local changes before receiving acknowledgment from the server.Implementing Sync Logic
I plan to use updatedAt for managing sync operations. I can outline the syncToServer() function as follows:
- Retrieve all notes where
syncStatus is not 'synced'.
- For each note, if
isDeleted is true, I'll send a DELETE request to /notes/:id. If successful, I can either delete the record from IndexedDB or archive it.
- For other notes, I'll send a PUT or POST request, depending on if it has a
serverId.
Though testing without a real server is tricky, I can still provide the code. I also need to implement syncFromServer() for loading initial data, which retrieves notes with a GET request to /notes and updates IndexedDB accordingly.
To prioritize offline functionality, I want to show data from IndexedDB first before syncing with the network in the background. It seems the user is looking for a clear template, so I'll provide an architecture overview followed by the main code, keeping the explanation concise.Building the Vue.js Offline Notes App
I’m organizing this around creating an app with offline editing and synchronization using IndexedDB. Here's how I'll approach it:
- Introduce features.
- Step 1: Set up a Vue 3 + Vite project with brief CLI commands.
- Step 2: Install the
idb library using npm install idb.
- Step 3: Create a
db.js wrapper for database operations with methods like getNotes, putNote, and deleteNote.
- Step 4: Create an
api.js stub for server endpoints.
- Step 5: Implement
syncService.js for syncing notes, using online status detection.
- Step 6: Create a Vue composable,
useNotes, for state management and methods like loadFromDb() and sync().
- Step 7: Design the main component
App.vue to render the UI and manage syncing.
- Step 8: Register a service worker for asset caching, clarifying its role in offline availability.
I’ll include sample code snippets for each step and consider keeping things concise but informative!Implementing Note Management
Here's how I’ll refine the note management functionality.
In db.js, I'll create essential functions:
getAllNotes() retrieves all notes.
putNote() updates or adds a note, setting syncStatus to 'pending' if necessary.
markNoteDeleted() flags a note as deleted.
For the API interactions in api.js, I'll treat the server's base URL and provide functions to fetch, upsert, and delete notes from the server.
The syncService.js will manage synchronization, pushing local changes and pulling the latest from the server. It will check if the user is online before proceeding, and include error handling to mark notes accordingly.
To avoid multiple writes during synchronization, I’ll create saveNoteLocal() for local saving and saveNoteFromServer() for handling server data updates. I'll ensure that deleteNoteLocal() marks notes as 'soft deleted' for pending sync. While offline, syncWithServer() won't trigger, and the UI will reflect each note's sync status clearly.
I'll aim for a balance between conceptual clarity and concise code!Designing Vue.js App Components
I’m sketching out the components of a Vue.js app to support offline editing with IndexedDB.
In App.vue, I’ll have a structure for showing notes, a form for creating/editing notes, and functionalities to handle online/offline syncing. The app will include features for displaying the sync status and managing notes.
The syncService.js will contain a function to manage online status. I need to add event listeners on mount, but I’ll also ensure to clean them up on unmount.
I’ll outline different sections in the final answer for clarity, covering the project setup, IndexedDB interactions, API layers, sync services, the main app component, and service workers, ensuring code consistency and easy adaptability.Implementing Database and API Functions
I’m outlining the implementation of functions for an offline notes app using IndexedDB.
First, I’ll set up global constants and a function to get the database instance using openDB. Next, I will create functions to manage notes, such as retrieving all notes, saving a note, marking a note as deleted, and syncing with the server.
In the API layer, I’ll define functions to fetch, upsert, and delete notes from a hypothetical RESTful server.
Additionally, I’ll stress the importance of handling note updates correctly while managing synchronization issues. Overall, the architecture needs to ensure smooth offline operation while maintaining data integrity.Defining App.vue Structure
I’m outlining the App.vue component of my offline notes app. It includes an interactive UI for managing notes, showing online/offline status, and enabling manual syncing.
The header displays the app title and synchronization status, while the main content includes a note editor and a list of notes. I’ll ensure to implement the saving, editing, and deleting functionalities, along with proper synchronization handling.
I’ll also handle event listeners for online status and incorporate some basic styling to create a user-friendly interface. It's all about balancing functionality and simplicity!Defining Manual Caching for Development
I'm outlining a manual caching setup for development purposes using a service worker. I'll define a cache name and the assets to cache for offline access. The install and activate events will help manage cache, ensuring we remove old versions.
While referencing /src/main.js might confuse in a production build, I'll recommend using a PWA plugin for that. Conciseness is key, so I might keep the service worker explanation short, while noting that offline editing persists in IndexedDB even without it. Also, I'll mention the use of placeholder URLs for future API calls! Below is a minimal but complete Vue 3 example that:
- Stores data offline in IndexedDB (via the
idb package).
- Lets you create/edit/delete notes while offline.
- Synchronizes changes to a backend API when you come back online.
- (Optionally) uses a simple service worker to cache the app shell for offline loading.
You can adapt it to any data model (tasks, customers, etc.) by changing the note fields.
1. Project setup
# Vue 3 + Vite scaffold
npm create vite@latest offline-notes -- --template vue
cd offline-notes
# IndexedDB helper
npm install idb
2. IndexedDB wrapper (src/db.js)
Uses idb to manage a notes object store with a syncStatus index.
// src/db.js
import { openDB } from 'idb';
const DB_NAME = 'offline-notes-db';
const DB_VERSION = 1;
const NOTES_STORE = 'notes';
let dbPromise;
function getDb() {
if (!dbPromise) {
dbPromise = openDB(DB_NAME, DB_VERSION, {
upgrade(db) {
if (!db.objectStoreNames.contains(NOTES_STORE)) {
const store = db.createObjectStore(NOTES_STORE, { keyPath: 'id' });
store.createIndex('syncStatus', 'syncStatus');
}
},
});
}
return dbPromise;
}
// Visible notes for UI (not deleted)
export async function getVisibleNotes() {
const db = await getDb();
const all = await db.getAll(NOTES_STORE);
return all.filter(n => !n.isDeleted);
}
// All notes, including deleted (for sync logic)
export async function getAllNotesRaw() {
const db = await getDb();
return db.getAll(NOTES_STORE);
}
// Notes that need to be pushed to the server
export async function getPendingNotes() {
const db = await getDb();
return db.getAllFromIndex(NOTES_STORE, 'syncStatus', 'pending');
}
// Save/update a note locally
export async function saveNoteLocal(note, { markPending = false } = {}) {
const db = await getDb();
const now = Date.now();
const id =
note.id ||
(self.crypto?.randomUUID ? self.crypto.randomUUID() : String(now));
const existing = await db.get(NOTES_STORE, id);
const record = {
...existing,
...note,
id,
updatedAt: now,
syncStatus: markPending
? 'pending'
: note.syncStatus || existing?.syncStatus || 'synced',
isDeleted: note.isDeleted ?? existing?.isDeleted ?? false,
};
await db.put(NOTES_STORE, record);
return record;
}
// Mark as deleted locally (soft delete), to be synced later
export async function markNoteDeletedLocal(id) {
const db = await getDb();
const existing = await db.get(NOTES_STORE, id);
if (!existing) return null;
existing.isDeleted = true;
existing.syncStatus = 'pending';
existing.updatedAt = Date.now();
await db.put(NOTES_STORE, existing);
return existing;
}
// Save what comes from server, always as synced + not deleted
export async function saveNoteFromServer(serverNote) {
const db = await getDb();
const existing = await db.get(NOTES_STORE, serverNote.id);
const record = {
...existing,
...serverNote,
syncStatus: 'synced',
isDeleted: false,
};
await db.put(NOTES_STORE, record);
return record;
}
// Hard-delete after server confirms deletion
export async function deleteNoteFromDb(id) {
const db = await getDb();
await db.delete(NOTES_STORE, id);
}
3. API layer (stub for your backend) – src/api.js
Replace BASE_URL with your actual API. If you don’t have one yet, you can temporarily just make these functions no-ops that resolve.
// src/api.js
const BASE_URL = 'https://your-api.example.com'; // <- change this
async function handleResponse(res) {
if (!res.ok) {
const text = await res.text();
throw new Error(`HTTP ${res.status}: ${text}`);
}
if (res.status === 204) return null;
return res.json();
}
export async function fetchNotesFromServer() {
const res = await fetch(`${BASE_URL}/notes`);
return handleResponse(res);
}
// Upsert note on server
export async function upsertNoteOnServer(note) {
const method = note.id ? 'PUT' : 'POST';
const url = note.id
? `${BASE_URL}/notes/${encodeURIComponent(note.id)}`
: `${BASE_URL}/notes`;
const res = await fetch(url, {
method,
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(note),
});
return handleResponse(res);
}
export async function deleteNoteOnServer(id) {
const res = await fetch(`${BASE_URL}/notes/${encodeURIComponent(id)}`, {
method: 'DELETE',
});
return handleResponse(res);
}
4. Sync service (src/sync.js)
Pushes local pending changes to the server, then pulls latest data back.
// src/sync.js
import {
getPendingNotes,
saveNoteFromServer,
deleteNoteFromDb,
getAllNotesRaw,
} from './db';
import {
fetchNotesFromServer,
upsertNoteOnServer,
deleteNoteOnServer,
} from './api';
export async function syncWithServer({ onNoteUpdated, onNoteDeleted } = {}) {
if (!navigator.onLine) return;
// 1. Push local changes
const pending = await getPendingNotes();
for (const note of pending) {
try {
if (note.isDeleted) {
await deleteNoteOnServer(note.id);
await deleteNoteFromDb(note.id);
onNoteDeleted && onNoteDeleted(note.id);
} else {
const savedOnServer = await upsertNoteOnServer(note);
const stored = await saveNoteFromServer(savedOnServer);
onNoteUpdated && onNoteUpdated(stored);
}
} catch (err) {
console.error('Error syncing note', note.id, err);
// Note stays 'pending'; will retry next sync
}
}
// 2. Pull from server
try {
const serverNotes = await fetchNotesFromServer();
const localNotes = await getAllNotesRaw();
const localMap = new Map(localNotes.map(n => [n.id, n]));
for (const serverNote of serverNotes) {
const local = localMap.get(serverNote.id);
const localUpdatedAt = local?.updatedAt || 0;
const serverUpdatedAt = serverNote.updatedAt || 0;
// Overwrite if:
// - we have no local version, or
// - local is synced and older than server
if (!local || (local.syncStatus === 'synced' && serverUpdatedAt > localUpdatedAt)) {
const stored = await saveNoteFromServer(serverNote);
onNoteUpdated && onNoteUpdated(stored);
}
}
} catch (err) {
console.error('Error pulling notes from server', err);
}
}
This is a simple conflict strategy: local unsynced edits win; synced-but-older copies are overridden by server. Improve this if you need more complex conflict resolution.
5. Vue root component (src/App.vue)
Offline editing UI + online status + sync button.
<!-- src/App.vue -->
<template>
<div class="app">
<header class="app-header">
<h1>Offline Notes</h1>
<div class="status">
<span :class="['badge', isOnline ? 'online' : 'offline']">
{{ isOnline ? 'Online' : 'Offline' }}
</span>
<button @click="manualSync" :disabled="!isOnline || isSyncing">
{{ isSyncing ? 'Syncing…' : 'Sync now' }}
</button>
<small v-if="lastSync">
Last sync: {{ lastSync.toLocaleTimeString() }}
</small>
</div>
</header>
<main class="layout">
<section class="editor">
<h2>{{ current.id ? 'Edit note' : 'New note' }}</h2>
<form @submit.prevent="saveCurrent">
<label>
Title
<input v-model="current.title" required />
</label>
<label>
Content
<textarea v-model="current.content" rows="5"></textarea>
</label>
<div class="buttons">
<button type="submit">Save locally</button>
<button type="button" v-if="current.id" @click="resetCurrent">
Cancel
</button>
</div>
<p class="hint">
Changes are stored in your browser immediately and synced when online.
</p>
</form>
</section>
<section class="list">
<h2>Your notes</h2>
<ul v-if="notes.length">
<li v-for="note in orderedNotes" :key="note.id" class="note">
<div class="note-main" @click="edit(note)">
<h3>{{ note.title }}</h3>
<p>{{ note.content }}</p>
</div>
<div class="note-meta">
<small>
Updated: {{ formatDate(note.updatedAt) }} ·
<span :class="['badge', note.syncStatus]">
{{ note.syncStatus }}
</span>
</small>
<button class="danger" @click.stop="remove(note)">Delete</button>
</div>
</li>
</ul>
<p v-else>No notes yet. Create one above.</p>
</section>
</main>
</div>
</template>
<script setup>
import { ref, computed, onMounted, onBeforeUnmount } from 'vue';
import { getVisibleNotes, saveNoteLocal, markNoteDeletedLocal } from './db';
import { syncWithServer } from './sync';
const notes = ref([]);
const current = ref(emptyNote());
const isOnline = ref(navigator.onLine);
const isSyncing = ref(false);
const lastSync = ref(null);
function emptyNote() {
return { id: null, title: '', content: '' };
}
const orderedNotes = computed(() =>
[...notes.value].sort((a, b) => (b.updatedAt || 0) - (a.updatedAt || 0))
);
async function loadNotes() {
notes.value = await getVisibleNotes();
}
async function saveCurrent() {
const saved = await saveNoteLocal(current.value, { markPending: true });
upsertInList(saved);
current.value = emptyNote();
if (navigator.onLine) await doSync();
}
async function remove(note) {
await markNoteDeletedLocal(note.id);
// hide from UI immediately
notes.value = notes.value.filter(n => n.id !== note.id);
if (navigator.onLine) await doSync();
}
function edit(note) {
current.value = { ...note };
}
function resetCurrent() {
current.value = emptyNote();
}
function upsertInList(note) {
const idx = notes.value.findIndex(n => n.id === note.id);
if (idx === -1) notes.value.unshift(note);
else notes.value[idx] = note;
}
async function doSync() {
if (isSyncing.value || !navigator.onLine) return;
isSyncing.value = true;
try {
await syncWithServer({
onNoteUpdated: upsertInList,
onNoteDeleted(id) {
notes.value = notes.value.filter(n => n.id !== id);
},
});
notes.value = await getVisibleNotes();
lastSync.value = new Date();
} finally {
isSyncing.value = false;
}
}
async function manualSync() {
await doSync();
}
function formatDate(ts) {
if (!ts) return '';
return new Date(ts).toLocaleString();
}
function handleOnline() {
isOnline.value = true;
void doSync();
}
function handleOffline() {
isOnline.value = false;
}
onMounted(async () => {
await loadNotes();
window.addEventListener('online', handleOnline);
window.addEventListener('offline', handleOffline);
if (navigator.onLine) {
void doSync();
}
});
onBeforeUnmount(() => {
window.removeEventListener('online', handleOnline);
window.removeEventListener('offline', handleOffline);
});
</script>
<style scoped>
.app {
max-width: 900px;
margin: 0 auto;
padding: 1rem;
font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
}
.app-header {
display: flex;
justify-content: space-between;
align-items: center;
gap: 1rem;
}
.status {
display: flex;
align-items: center;
gap: 0.5rem;
}
.layout {
display: grid;
grid-template-columns: 1fr 1.2fr;
gap: 1rem;
margin-top: 1rem;
}
@media (max-width: 768px) {
.layout {
grid-template-columns: 1fr;
}
}
.editor form {
display: flex;
flex-direction: column;
gap: 0.5rem;
}
.editor input,
.editor textarea {
width: 100%;
box-sizing: border-box;
}
.buttons {
display: flex;
gap: 0.5rem;
}
.hint {
font-size: 0.8rem;
color: #555;
}
.list ul {
list-style: none;
padding: 0;
margin: 0;
}
.note {
border: 1px solid #ddd;
padding: 0.5rem;
margin-bottom: 0.5rem;
border-radius: 4px;
}
.note-main {
cursor: pointer;
}
.note-meta {
display: flex;
justify-content: space-between;
align-items: center;
margin-top: 0.25rem;
}
.badge {
padding: 0.15rem 0.4rem;
border-radius: 999px;
font-size: 0.75rem;
}
.online {
background: #d1fae5;
color: #065f46;
}
.offline {
background: #fee2e2;
color: #991b1b;
}
.pending {
background: #fef3c7;
color: #92400e;
}
.synced {
background: #e0f2fe;
color: #075985;
}
.danger {
background: #dc2626;
color: white;
border: none;
padding: 0.25rem 0.6rem;
border-radius: 3px;
cursor: pointer;
}
button[disabled] {
opacity: 0.5;
cursor: default;
}
</style>
6. Entry point (src/main.js)
// src/main.js
import { createApp } from 'vue';
import App from './App.vue';
createApp(App).mount('#app');
// Optional: register service worker for offline app shell
if ('serviceWorker' in navigator) {
window.addEventListener('load', () => {
navigator.serviceWorker
.register('/service-worker.js')
.catch(err => console.error('SW registration failed', err));
});
}
7. (Optional) Service worker for offline loading
For Vite, put this file in public/service-worker.js so it’s served as /service-worker.js.
// public/service-worker.js
const CACHE_NAME = 'offline-notes-cache-v1';
const ASSETS = [
'/', // index.html
'/index.html'
// In a real app, use a PWA plugin to inject built asset paths.
];
self.addEventListener('install', event => {
event.waitUntil(caches.open(CACHE_NAME).then(cache => cache.addAll(ASSETS)));
self.skipWaiting();
});
self.addEventListener('activate', event => {
event.waitUntil(
caches
.keys()
.then(keys =>
Promise.all(keys.filter(k => k !== CACHE_NAME).map(k => caches.delete(k)))
)
);
self.clients.claim();
});
self.addEventListener('fetch', event => {
const { request } = event;
if (request.method !== 'GET') return;
event.respondWith(
caches.match(request).then(cached => {
if (cached) return cached;
return fetch(request).catch(() => cached);
})
);
});
For production, prefer a proper PWA setup (e.g. vite-plugin-pwa) that handles hashed filenames and caching strategies.
8. How it behaves
- App startup:
- Loads existing notes from IndexedDB (
getVisibleNotes()).
- If online, runs
syncWithServer() to push/pull changes.
- Editing while offline:
saveNoteLocal() immediately persists to IndexedDB with syncStatus: 'pending'.
- UI shows the note with status
"pending".
- When connection returns:
online event triggers doSync().
- Pending notes are pushed to the server; server-confirmed versions are saved back as
"synced".
- New/updated server notes are pulled down and merged.
If you want, I can next help you:
- Stub the API layer so you can run this fully without a real backend.
- Extend this pattern for more complex data models or relationships.