LocalStorage With Vue.js Persisting And Summing JSON Column Values
Hey guys! 👋 Ever found yourself needing to store data locally in a web app and then perform some calculations on it? Today, we're diving deep into how to use LocalStorage with Vue.js to persist data and, more specifically, how to recover and sum values from a JSON column stored in LocalStorage. This is super useful when you need to keep track of totals, like in a shopping cart or a financial dashboard. Let’s break it down!
Understanding the Goal: Persisting and Summing Data Locally
So, what’s the mission here? The main goal is to locally persist sums (think value * times
) and then add up all these results using Vue.js. Imagine you have a series of calculations that you want to keep even if the user refreshes the page or closes the browser. That’s where LocalStorage comes in handy. We'll store our data as JSON, which is perfect for complex data structures, and then use Vue.js to dynamically display and update the sums.
Why LocalStorage?
LocalStorage is a web storage API that allows you to store key-value pairs in a web browser. The data stored in LocalStorage persists even after the browser is closed and reopened, making it ideal for saving user preferences, application states, or, in our case, calculation results. Unlike cookies, LocalStorage has a much larger storage capacity (typically around 5MB), and the data is not sent to the server with every HTTP request, which helps improve performance.
Why Vue.js?
Vue.js is a progressive JavaScript framework for building user interfaces. It’s known for its simplicity, flexibility, and powerful features like data binding and component-based architecture. Vue.js makes it easy to manage and manipulate the data we retrieve from LocalStorage, and its reactivity system ensures that our UI stays in sync with the data.
The Data Structure
Let's talk about the data we're going to persist. We have a structure that looks something like this:
data: {
nameApp: 'App',
somaValor: {
// ... our data will go here
}
}
Inside somaValor
, we’ll store the individual sums that we want to keep track of. Each entry in somaValor
will represent a calculation result, and we'll need to add them all up to get the grand total. This structure is flexible and can be adapted to various scenarios, whether you’re tracking sales, expenses, or any other kind of numerical data.
Step-by-Step Implementation
Alright, let’s get our hands dirty with some code! We’ll walk through the process step by step, from setting up our Vue.js application to reading and writing data to LocalStorage, and finally, calculating the sum.
1. Setting Up the Vue.js Application
First things first, we need to set up a Vue.js application. If you're starting from scratch, you can use the Vue CLI or simply include Vue.js in your HTML file via CDN. For this example, let's assume we have a basic Vue instance:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>LocalStorage Summation with Vue.js</title>
<script src="https://cdn.jsdelivr.net/npm/vue@2"></script>
</head>
<body>
<div id="app">
<!-- Our Vue app content will go here -->
</div>
<script>
new Vue({
el: '#app',
data: {
nameApp: 'App',
somaValor: {}
},
mounted() {
// We'll add our LocalStorage logic here
},
computed: {
// We'll add our computed property for the sum here
},
methods: {
// We'll add methods to interact with LocalStorage here
}
});
</script>
</body>
</html>
In this basic setup, we have a Vue instance attached to a div with the ID app
. We’ve also defined a data
object with nameApp
and somaValor
, an empty object that will hold our sums. The mounted
lifecycle hook is where we'll load data from LocalStorage when the component is created. We also have placeholders for computed
properties and methods
, which we’ll use to calculate the sum and interact with LocalStorage.
2. Persisting Data to LocalStorage
Now, let’s create a method to save our data to LocalStorage. We’ll call this method saveToLocalStorage
. This method will take the somaValor
object and store it in LocalStorage as a JSON string.
methods: {
saveToLocalStorage() {
localStorage.setItem('somaValorData', JSON.stringify(this.somaValor));
}
}
Here’s what’s happening:
- We use
localStorage.setItem
to store the data. - The first argument,
'somaValorData'
, is the key we’ll use to retrieve the data later. - The second argument is the value we want to store. Since LocalStorage only accepts strings, we use
JSON.stringify
to convert oursomaValor
object into a JSON string.
3. Retrieving Data from LocalStorage
Next, we need to retrieve the data from LocalStorage when our Vue component is mounted. We’ll do this in the mounted
lifecycle hook. We’ll call a method loadFromLocalStorage
to handle this.
mounted() {
this.loadFromLocalStorage();
},
methods: {
loadFromLocalStorage() {
const storedData = localStorage.getItem('somaValorData');
if (storedData) {
this.somaValor = JSON.parse(storedData);
}
},
saveToLocalStorage() {
localStorage.setItem('somaValorData', JSON.stringify(this.somaValor));
}
}
Here’s the breakdown:
- We use
localStorage.getItem
to retrieve the data using the key'somaValorData'
. - If there’s data stored (i.e.,
storedData
is notnull
), we useJSON.parse
to convert the JSON string back into a JavaScript object. - We then assign this object to our
this.somaValor
data property, making it available in our Vue component. - This ensures that every time the component is mounted (like on a page refresh), we load the data from LocalStorage.
4. Calculating the Sum with a Computed Property
Now, let’s calculate the sum of the values in our somaValor
object. We’ll use a computed property for this, which will automatically update whenever the somaValor
object changes. 👨💻
computed: {
totalSum() {
let sum = 0;
for (let key in this.somaValor) {
if (this.somaValor.hasOwnProperty(key)) {
sum += this.somaValor[key];
}
}
return sum;
}
}
Here’s what’s going on:
- We define a computed property called
totalSum
. - We initialize a
sum
variable to 0. - We loop through the keys in the
this.somaValor
object. - For each key, we add its value to the
sum
variable. - Finally, we return the total
sum
. - The
hasOwnProperty
check ensures we only iterate over the object's own properties, not inherited ones.
5. Adding Data and Saving to LocalStorage
Let’s add a method to add new values to our somaValor
object and save it to LocalStorage. We’ll call this method addValue
.
methods: {
loadFromLocalStorage() {
const storedData = localStorage.getItem('somaValorData');
if (storedData) {
this.somaValor = JSON.parse(storedData);
}
},
saveToLocalStorage() {
localStorage.setItem('somaValorData', JSON.stringify(this.somaValor));
},
addValue(key, value) {
Vue.set(this.somaValor, key, value);
this.saveToLocalStorage();
}
}
Key points:
- The
addValue
method takes akey
and avalue
as arguments. - We use
Vue.set
to add the new key-value pair to thesomaValor
object. This is important because Vue.js needs to be aware of the new property to maintain reactivity. - After adding the value, we call
this.saveToLocalStorage()
to persist the changes.
6. Displaying the Data in the Template
Now, let’s display the data in our Vue.js template. We’ll show the individual values in somaValor
and the total sum.
<div id="app">
<h1>{{ nameApp }}</h1>
<div>
<h2>Values:</h2>
<ul>
<li v-for="(value, key) in somaValor" :key="key">
<strong>{{ key }}:</strong> {{ value }}
</li>
</ul>
</div>
<div>
<h2>Total Sum:</h2>
<p><strong>{{ totalSum }}</strong></p>
</div>
<div>
<h2>Add New Value:</h2>
<input type="text" v-model="newKey" placeholder="Key">
<input type="number" v-model="newValue" placeholder="Value">
<button @click="addValue(newKey, newValue)">Add</button>
</div>
</div>
In this template:
- We display the
nameApp
in an<h1>
tag. - We use a
v-for
loop to iterate over thesomaValor
object and display each key-value pair in a list item. - We display the
totalSum
computed property in a<p>
tag. - We have input fields for a new key and value, and a button that calls the
addValue
method when clicked. - We need to add
newKey
andnewValue
to our data object to make the input fields work.
7. Final Code and Enhancements
Here’s the complete code for our Vue.js application:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>LocalStorage Summation with Vue.js</title>
<script src="https://cdn.jsdelivr.net/npm/vue@2"></script>
</head>
<body>
<div id="app">
<h1>{{ nameApp }}</h1>
<div>
<h2>Values:</h2>
<ul>
<li v-for="(value, key) in somaValor" :key="key">
<strong>{{ key }}:</strong> {{ value }}
</li>
</ul>
</div>
<div>
<h2>Total Sum:</h2>
<p><strong>{{ totalSum }}</strong></p>
</div>
<div>
<h2>Add New Value:</h2>
<input type="text" v-model="newKey" placeholder="Key">
<input type="number" v-model="newValue" placeholder="Value">
<button @click="addValue(newKey, newValue)">Add</button>
</div>
</div>
<script>
new Vue({
el: '#app',
data: {
nameApp: 'App',
somaValor: {},
newKey: '',
newValue: 0
},
mounted() {
this.loadFromLocalStorage();
},
computed: {
totalSum() {
let sum = 0;
for (let key in this.somaValor) {
if (this.somaValor.hasOwnProperty(key)) {
sum += Number(this.somaValor[key]);
}
}
return sum;
}
},
methods: {
loadFromLocalStorage() {
const storedData = localStorage.getItem('somaValorData');
if (storedData) {
this.somaValor = JSON.parse(storedData);
}
},
saveToLocalStorage() {
localStorage.setItem('somaValorData', JSON.stringify(this.somaValor));
},
addValue(key, value) {
Vue.set(this.somaValor, key, Number(value));
this.saveToLocalStorage();
this.newKey = '';
this.newValue = 0;
}
}
});
</script>
</body>
</html>
Key improvements and additions:
- Added
newKey
andnewValue
to the data object for the input fields. These are bound to the input elements usingv-model
. - Updated the
addValue
method to resetnewKey
andnewValue
after adding a new value, which clears the input fields. - Ensured that values added to
somaValor
are treated as numbers by usingNumber(value)
when adding to the sum and when setting the value. - Added
Number()
when calculating the sum to ensure that the values are treated as numbers, even if they were stored as strings in LocalStorage.
Further Enhancements
- Error Handling: Add error handling for cases where LocalStorage might be full or unavailable.
- Input Validation: Validate the input values to ensure they are numbers.
- Dynamic UI Updates: Use Vue.js reactivity to update the UI dynamically whenever a value is added or changed.
- Modularization: Break the code into reusable components for better organization and maintainability.
Conclusion
And there you have it! We’ve successfully created a Vue.js application that persists data to LocalStorage and calculates the sum of those values. This is a powerful technique for building web applications that need to store and manipulate data locally. Remember, the key is to understand the data flow and how Vue.js reactivity and LocalStorage persistence work together. Keep experimenting, and you’ll become a master of data persistence in no time! 🚀