- Forums
- vuejs
- VueJs Local Storage setItem() to Save and Get Variable In Browser Storage
use this code to set and retrieve local storage saved variable in browser. [5255], Last Updated: Mon Jun 24, 2024
edwin
Tue Dec 19, 2023
0 Comments
197 Visits
For this example, we want to save the theme settings to either light or dark based on bootstrap bg-xxx color class.
Template:
<template>
<nav
:class="[`navbar-${theme}`, `bg-${theme}`, 'navbar', 'navbar-expand-lg']"
>
Script:
<script>
import NavbarLink from './NavbarLink.vue';
export default {
components: {
NavbarLink
},
created(){
this.getThemeSettings();
},
props: ['pages', 'activePage', 'navLinkClick'],
data() {
return {
theme: 'light',
}
},
methods: {
changeTheme() {
let theme = 'light';
if (this.theme == 'light') {
theme = 'dark';
}
this.theme = theme;
this.storeThemeSettings();
},
storeThemeSettings(){
localStorage.setItem('theme', this.theme);
},
getThemeSettings(){
let theme = localStorage.getItem('theme');
if(theme){
this.theme = theme;
}
}
}
}
</script>
1GNsWa_EZdw