Persistence Example
This example demonstrates the built-in persistence plugin. The state below is automatically saved to localStorage and will persist across page reloads.
Persistence Demo
Try reloading the page! The data below is persisted in localStorage.
Shopping List
List is empty
Source Code
Store Definition
typescript
import { defineStore } from 'xds'
import { ref, reactive } from 'vue'
export const usePersistenceStore = defineStore('persistence-example', () => {
// Simple state
const user = reactive({
name: '',
email: '',
})
// Nested state
const settings = reactive({
darkMode: false,
notifications: true,
})
// Array state
const items = ref<string[]>([])
function addItem(item: string) {
items.value.push(item)
}
function removeItem(index: number) {
items.value.splice(index, 1)
}
function $reset() {
user.name = ''
user.email = ''
settings.darkMode = false
settings.notifications = true
items.value = []
}
return {
user,
settings,
items,
addItem,
removeItem,
$reset,
}
})Component
vue
<script setup lang="ts">
import { usePersistenceStore } from './store'
import { ref } from 'vue'
const store = usePersistenceStore()
const newItem = ref('')
function addItem() {
if (newItem.value.trim()) {
store.addItem(newItem.value)
newItem.value = ''
}
}
</script>
<template>
<div class="demo-container">
<div class="card">
<h3>Persistence Demo</h3>
<p class="desc">Try reloading the page! The data below is persisted in localStorage.</p>
<div class="input-group">
<input v-model="store.user.name" placeholder="Enter your name" />
<div class="theme-toggle">
<label>
<input type="checkbox" v-model="store.settings.darkMode" />
Dark Mode
</label>
</div>
</div>
<div class="todo-list">
<h4>Shopping List</h4>
<div class="add-item">
<input v-model="newItem" @keyup.enter="addItem" placeholder="Add item..." />
<button @click="addItem">Add</button>
</div>
<ul>
<li v-for="(item, index) in store.items" :key="index">
{{ item }}
<button class="delete-btn" @click="store.removeItem(index)">×</button>
</li>
</ul>
<p v-if="store.items.length === 0" class="empty-tip">List is empty</p>
</div>
<div class="actions">
<button @click="store.$reset">Reset All Data</button>
</div>
</div>
</div>
</template>Configuration
Enable the persistence plugin in your app entry point (e.g., .vitepress/theme/index.ts for this docs site).
typescript
import { xds, persistence } from 'xds'
app.use(
xds({
plugins: [
persistence({
enable: ['persistence-example'],
}),
],
}),
)