How to use Vue with sessionStorage
Using sessionStorage in Vue applications maintains state during the browser session, perfect for temporary data like form drafts or wizard steps. As the creator of CoreUI, a widely used open-source UI library, I’ve implemented sessionStorage integration in Vue applications throughout my 11 years of framework development. The most practical approach is combining Vue’s reactivity with sessionStorage using watchers for automatic synchronization. This method provides session-scoped persistence that clears when the browser tab closes.
Use watchers to sync Vue state with sessionStorage automatically.
import { ref, watch, onMounted } from 'vue'
export default {
setup() {
const formData = ref({
name: '',
email: '',
step: 1
})
onMounted(() => {
const saved = sessionStorage.getItem('formData')
if (saved) {
formData.value = JSON.parse(saved)
}
})
watch(formData, (newValue) => {
sessionStorage.setItem('formData', JSON.stringify(newValue))
}, { deep: true })
return { formData }
}
}
Here the component loads saved data from sessionStorage when mounted, parsing the JSON string back into an object. A deep watcher monitors the formData object and automatically saves changes to sessionStorage. The deep: true option ensures nested property changes trigger the watcher. Data persists during the session but clears when the tab closes.
Best Practice Note:
This is the pattern we use in CoreUI Vue components for multi-step forms and temporary session data. Always wrap sessionStorage operations in try-catch blocks for error handling, create composables for reusable sessionStorage logic, and remember that sessionStorage is tab-specific unlike localStorage which is shared across tabs.



