Watchers & onMounted
What is a watcher?
In the Vue 3 Composition API, a watcher keeps an eye on your reactive data and responds whenever that data changes.
Basic syntax
The watch()
function takes two main arguments:
- Source: The reactive data to watch.
- Callback: A function to run when the data changes.
watch(source, callback, options)
The watch()
function
The watch()
function allows you to monitor reactive references (E.g. ref()
) and execute side effects when their values change. Unlike computed properties that return values, watchers are designed for performing actions such as updating the DOM.
import { ref, watch } from 'vue'
const username = ref('')
const message = ref('')
watch(username, (newName) => {
if (newName) {
message.value = `Welcome back, ${newName}!`
} else {
message.value = 'Please enter your name'
}
})
Currently in our project, when the browser is reloaded the showPastEvents
value is reset. We will be using the watch()
function to store this value into local storage.
What is localStorage
?
This is a web browser feature to store data locally on the user's device. Unlike regular variables/data that disappear when the page refreshes, localStorage
values will persist in the browser when closed and reopened.
localStorage
stores data as key-value pairs in strings, meaning we need to convert objects to JSON
when storing them and parse them when retrieving values. This is regular JavaScript and not specific to Vue.js.
// Storing data
localStorage.setItem('name', 'Homer')
localStorage.setItem('settings', JSON.stringify({ theme: 'dark' }))
// Retrieving data
const name = localStorage.getItem('name') // 'Homer'
const settings = JSON.parse(localStorage.getItem('settings')) // { theme: 'dark' }
Using watch
In the App.vue
, include the watch
import from the Vue library:
import { ref, computed, watch } from "vue";
Below the showPastEvents
variable, set up the watch()
function:
const showPastEvents = ref(true);
watch(
showPastEvents,
(newValue) => {
localStorage.setItem("showPastEvents", JSON.stringify(newValue));
}
);
watch(showPastEvents, ...)
: Watches for changes to theshowPastEvents
variable.(newValue) => { ... }
: Callback function to run when the value changes.localStorage.setItem("showPastEvents", ...)
: Saves the new value to browser storage.JSON.stringify(newValue)
: Converts the boolean value to a string to store in the browser.
We also need a way to check the values in local storage when a component mounts, for this we can use onMounted
.
What is onMounted
?
The onMounted
hook is a Vue 3 Composition API lifecycle hook which runs when the component is mounted to the DOM. Used to perform setup and initial tasks like setting event listeners, API calls, and loading data from localStorage.
Once your component is fully rendered and ready to go, onMounted
gives you a safe place to run any code that needs the DOM to be available.
Using onMounted
First add onMounted
to the list of Vue imports:
import { ref, computed, watch, onMounted } from "vue";
Below the watch()
function, add the onMounted()
function:
onMounted(() => {
const saved = localStorage.getItem("showPastEvents");
if (saved !== null) {
showPastEvents.value = JSON.parse(saved);
}
});
onMounted(() => { ... })
- To run when the component is first loaded.localStorage.getItem("showPastEvents")
- Get the saved value from browser storage.if (saved !== null)
- Checks if a value was saved in local storage.JSON.parse(saved)
- Converts the string back to the original boolean value.showPastEvents.value = ...
- Updates the variable with the saved value from storage.