In this tutorial, we will create a simple Vue 3 application that utilizes the browser’s local storage. We will start by importing the necessary modules from Vue, including the ref function and the onMounted hook.
Example
<script>
import { ref, onMounted } from "vue";
const inputValue = ref('')
const localStorageValue = ref('')
onMounted(() => {
showLocalStorageContent()
})
const setLocalStorageContent = () => {
localStorage.setItem('item', inputValue.value)
}
const showLocalStorageContent = () => {
localStorageValue.value = localStorage.getItem('item')
}
const removeLocalStorageContent = () => {
localStorageValue.value = localStorage.removeItem('item')
}
</script>
<template>
<div>
<input type="text" v-model="inputValue" placeholder="Enter value" />
<div>
<button @click="setLocalStorageContent">Set local storage</button>
<button @click="removeLocalStorageContent">Remove local storage</button>
</div>
<div style="margin-top: 20px">
<button @click="showLocalStorageContent">Show local storage content</button>
<p>
Value of 'item' is {{ localStorageValue }}
</p>
</div>
</div>
</template>
Code language: HTML, XML (xml)
Explanation
First, we will create a reactive state called inputValue which will be used to store the value entered by the user in the input field. We will also create a ref called localStorageValue which will be used to store the value retrieved from local storage.
When the component is mounted, we will use the onMounted hook to call the showLocalStorageContent function. This function will display the current value of ‘item‘ from local storage.
We will then create three functions: setLocalStorageContent, showLocalStorageContent and removeLocalStorageContent.
- setLocalStorageContent function will set the value of ‘item’ in local storage to the value entered by the user in the input field.
- showLocalStorageContent function will retrieve the value of ‘item’ from local storage and display it on the screen.
- removeLocalStorageContent function will remove the ‘item’ from local storage.
In the template, we will add an input field that is bound to the inputValue ref. We will also add two buttons, one to set the local storage and one to remove the local storage. We will also add a button to show the content of the local storage.
Finally, we will display the value of ‘item‘ from local storage on the screen.
To use the above code, copy and paste it into a .vue file in your project and then use it as a component.
If you have any doubts or suggestions, please sound off in the comments below!