Is It Possible to Save Data to Local Storage Using Vue.js?

I am currently working on storing data using Vue.js and local storage.

By writing localStorage.set('something', 5) in my main.js file, I can view the data in the Chrome dev tools under the 'Storage' section in the 'Application' panel.

However, when it comes to storing other data that I intend to use, I am facing an issue. This code is located within the 'methods: {}' section of my App.vue parent component. I suspect this might be causing the problem, but being new to Vue, I am unsure about where to place my code in order for the data to appear in local storage in the dev tools.

The code snippet presented here is merely to indicate its position, not its operation.

// App.vue
data() {
  return {
    healthScore: 0,
    storedHealthScore: 0
  }
},
methods: {
  setHealthScore() {
    localStorage.setItem('HealthScore', this.healthScore)
},
  getHealthScore() {
    this.storedHealthScore = localStorage.getItem('HealthScore')
},
  removeHealthScore() {
    localStorage.removeItem('HealthScore')
  }
}

Could you kindly guide me on where I should put my code so that the data appears correctly in local storage?

Answer №1

Regardless of the file in which you're storing data, it remains accessible across your entire website. Ensure that your setHealthScore() function is functioning properly as well.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to transform an HTML <script> tag into React code?

I am new to the world of JavaScript and React. Can someone help me convert the script below into a React component? <div id="SOHUCS" sid="xxx"></div> <script charset="utf-8" type="text/javascript" sr ...

Encountered an error trying to access the length property of an undefined variable while passing props

I need help with my shopping app project. I am trying to create a feature where if the cart is empty, it should display a message saying "shopping cart is empty." However, when I try to implement this, I keep getting a type error that says "Cannot read p ...

Is there a way to send a promise resolve or reject from a function code within router.post() in Express?

Below is my code in express (node.js) router.post('/example.json', function (req, res) { // getFileInfo is a function to return an array return getFileInfo(req.body.fileList).then((array) => { axios({ method: 'post', ...

The sequencing of AJAX calls on the server side may not necessarily match the order in which they were initiated on the client side

I am working on an ASP.NET MVC application that includes a JavaScript function within a view. Here is the code snippet: function OnAmountChanged(s, fieldName, keyValue, url) { console.log("Get Number: " + s.GetNumber()); console.log(" "); ...

Decrease the gap between the ticks on a horizontal bar chart in ChartJS

Currently, I am utilizing the horizontal bar chart feature from chartjs and encountering an issue with the chart appearing too large. In addition, there is a notable gap between the ticks on the xAxis (as shown in the attached image). Does anyone know how ...

What is the best way to split an input field into distinct fields for display on the screen?

Take a look at this image: https://i.stack.imgur.com/LoVqe.png I am interested in creating a design similar to the one shown in the image, where a 4 digit one-time password (OTP) is entered by the user. Currently, I have achieved this by using 4 separate ...

Creating a stylish CSS button with split colors that run horizontally

Could you please provide some guidance on creating a button design similar to this one? I've made progress with the code shown below, but still need to make adjustments like changing the font. <!DOCTYPE html> <html> <head> <sty ...

Exploring the functionalities of Stripe's latest Search API integrated with metadata features

I'm currently working on a project to showcase products stored in the Stripe Database. I attempted to implement this using if statements, filters, and the new Search API of Stripe, but unfortunately, my attempts were unsuccessful. Any ideas on what el ...

Distributing your React component on npm

I've been working on a React component for over a week now and I'm struggling to publish it on NPM. The lack of credible resources online has made this process challenging for me. Can anyone offer step-by-step guidance or recommend reliable reso ...

Ejs does not automatically include the message when returning a template to render in HTML

I need help rewording the title properly. I am facing an issue in my server code where a database query is executed to check if the account name already exists. If it does, a specific message should be displayed using this template: con.query('SELECT ...

When dealing with dynamic components, vue-meta fails to consistently show the title, content, or schema upon page refresh or when clicking on an

After navigating to my dynamic components via the navigation bar, I noticed that the Vue-meta title, content, and schema are displayed correctly. However, upon refreshing the page or clicking on an external link, I encountered the issue of receiving a valu ...

Display Material Popup in Angular before user leaves the page

My goal is to display an Angular Material Dialog Box (Popup window) when the user clicks the Chrome Window Close button. The Dialog modal should prompt the user if they want to save changes or cancel. However, the modal only appears for a brief moment and ...

Unable to convert JavaScript object to C# through deserialization

In order to pass a model from the controller action to the view, I included a list of objects and converted it into a JavaScript object to facilitate displaying markers on Google Maps. My goal is to send the selected object (selected marker) back to the co ...

Avoid cascading of the 'display' property in JavaScript styling to prevent inheritance

Is there a way in Javascript to toggle the visibility of a larger portion of HTML without affecting inner display properties with display: <value>? Despite setting an outer display property using Javascript, the inner display properties are also alt ...

The operation malfunctions if the variable input is below 50, causing it to produce inaccurate results

The function "calcFinalTotal()" was created to calculate the post-tax discount on a purchase of items that were previously totaled and stored in an input tag with the ID of "totaltaxamount". This function applies a 10% discount to orders between $50 to $ ...

Issues with variable usage in vue 3.2 setup script when utilizing the composition API in vue-i18n-next

Currently, in my Vue 3.2 project, I am utilizing vue-i18n-next v9 along with the composition API and the <script setup> method. I am attempting to generate a translated message that includes placeholders indicated by {}. For example: export default ...

Guide on populating a series of rectangles in a line based on values stored in an array using d3.js

I have 100 rectangles arranged in a 10x10 square. My goal is to assign colors to the rectangles based on values from an array var avg = [1, 4, 4, 7, 11, 15, 58] I'm facing an issue at the value 4 being repeated and I find the current code quite mess ...

Automatically populate email fields with pre-filled form data

Looking to create an HTML form that utilizes JS/jQuery (no PHP) to capture data from "subject" and "message" fields and send an email. The goal is for the client-side code to open the user's mail client, pre-fill the subject and body with form data, a ...

Utilizing pop-up info boxes

After thoroughly reviewing the documentation on Imagemapster's website and browsing several posts, I am still struggling to get the tooltips working correctly. I attempted to share my HTML and JS code on jsfiddle.com without success, so I have provide ...

Can I obtain a link through the branch_match_id parameter?

Within my application, there exists a hyperlink: hxxp://get.livesoccer.io/IuKk/0CRq5vArLx which leads to the following destination: hxxp://livesoccer.io/news.html?url=http%3A%2F%2Fwww.90min.com%2Fembed%2Fposts%2F4003374-chelsea-star-pedro-loving-life-at-s ...