Web storage is a fundamental aspect of web development, allowing us to store data locally in a user’s browser. Vue.js, a popular JavaScript framework, provides a simple and efficient way to work with web storage through various plugins. In this beginner-friendly guide, we’ll explore Vue Web Storage, a convenient solution for managing local storage and session storage in Vue.js applications.
Understanding Web Storage
Before diving into Vue Web Storage, let’s grasp the basics of web storage. There are two types: local storage and session storage. Local storage persists data across browser sessions, while session storage retains data only for the duration of a single browser session.
Setting Up a Vue Project
Begin by setting up a new Vue.js project using the Vue CLI. Open your terminal and run:
vue create vue-web-storage-example
Navigate to the project directory:
cd vue-web-storage-example
Installing Vue Web Storage
Install the vue-web-storage
package to simplify working with web storage in your Vue.js application:
npm install vue-web-storage --save
Using Vue Web Storage
Once installed, integrating Vue Web Storage into your Vue.js application is straightforward. Open the component where you want to use web storage, and import the necessary modules:
// src/components/MyComponent.vue
<template>
<div>
<h1>Vue Web Storage Example</h1>
<div>
<label for="dataInput">Enter Data:</label>
<input v-model="dataInput" type="text" id="dataInput" />
<button @click="saveToLocalStorage">Save to Local Storage</button>
<button @click="saveToSessionStorage">Save to Session Storage</button>
</div>
<div>
<h2>Stored Data:</h2>
<p>Local Storage: {{ $localStorage.data }}</p>
<p>Session Storage: {{ $sessionStorage.data }}</p>
</div>
</div>
</template>
<script>
export default {
data() {
return {
dataInput: '',
};
},
methods: {
saveToLocalStorage() {
this.$localStorage.data = this.dataInput;
},
saveToSessionStorage() {
this.$sessionStorage.data = this.dataInput;
},
},
};
</script>
In this example, we’re using Vue Web Storage to save and retrieve data from both local storage ($localStorage
) and session storage ($sessionStorage
). The saveToLocalStorage
and saveToSessionStorage
methods store the entered data, and the stored data is then displayed in the template.
Complete project of a minimalistic Vue.js plugin for web storage
Follow these steps to use Vue web storage
Version matrix
Vue.js version | Package version | Branch |
---|---|---|
2.x | 5.x | 5.x |
3.x | 6.x | master |
Features
- Choose either
localStorage
orsessionStorage
or both - Prefix all of your stored keys
- Auto
JSON.stringify
andJSON.parse
- Events for cross tab communication
Installation
# yarn yarn add vue-web-storage # npm npm install vue-web-storage
Usage
import {createApp} from 'vue'; import StoragePlugin from 'vue-web-storage'; const app = createApp({}).mount('#app') app.use(StoragePlugin); // Use in your components // this.$localStorage
Configuration (optional)
app.use(StoragePlugin, { prefix: 'your_app_slug_',// default `app_` drivers: ['session', 'local'], // default 'local' }); // It will register two different instances // this.$sessionStorage // this.$localStorage
Methods
All methods take care of prefix in key name, so you no need to specify the prefix when using them.
set(key,value)
Stores the value under specified key in storage. Convert value to JSON before saving. This method throws error on failure.
this.$localStorage.set('name', 'john') this.$localStorage.set('isAdmin', true) this.$localStorage.set('roles', ['admin', 'sub-admin']) this.$localStorage.set('permission', {id: 2, slug: 'edit_post'})
get(key, ?defaultValue = null)
Retrieves given key value from storage, parse the value from JSON before returning. If parsing failed then throws error
this.$localStorage.get('name') this.$localStorage.get('doesNotExistsInStorage', 'defaultValue')
remove(key)
Removes the individual key
from storage
this.$localStorage.remove('name')
clear(?force = false)
Returns array of keys stored in storage. Passing true will return prefixed key names.
this.$localStorage.keys()
hasKey(key)
Returns true
if key exists in storage regardless of its value.
this.$localStorage.hasKey('name')
length()
Returns the number of keys stored in storage
this.$localStorage.length()
Events
💡 These are not regular Vue.js events, these events to be used for cross tab communication.
on(key,fn)
Attaches a listener method to the given key. You can attach multiple methods on the same key.
const onChangeName = (newValue, OldValue, originUrl) => { // do something when `name` value gets changed }; this.$localStorage.on('name', onChangeName); this.$localStorage.on('name', this.anotherMethod)
off(key,fn)
Removes specified listener method form the given key.
this.$localStorage.off('name', this.onChangeName)
clearEvents(?key)
Removes all listeners for the given key otherwise clears the listeners pool when key not specified.
this.$localStorage.clearEvents('name'); this.$localStorage.clearEvents()
Install in non-module environments (without webpack)
<!-- Vue js --> <script src="https://cdn.jsdelivr.net/npm/vue@3"></script> <!-- Lastly add this package --> <script src="https://cdn.jsdelivr.net/npm/vue-web-storage@6"></script> <!-- Init the plugin --> <script> yourApp.use(VueWebStorage.default) </script>
Testing
- This package is using Jest for testing
- Tests can be found in
__test__
folder. - Execute tests with this command
yarn test