Storing an array element in the cache with Vue.js when submitted through a form

I'm facing an issue with saving my input to the cache memory. I attempted to utilize the mounted method, but it's not performing as desired because it fails to retain the last input in memory; upon refreshing the page, the last input gets erased. It's possible that I'm making a mistake since I've only just started learning Vue a day ago. Can someone please clarify what's incorrect here or provide guidance on how to rectify it?

export default {
  name: 'Skills',
  data() {
    return {
      skill: '',
      skills: [
        { 'skill': 'Vue.js' },
        { 'skill': 'Frontend Developer' }
      ]
    }
  },
  mounted() {
    if (localStorage.skill) {
      this.skill = localStorage.skill;
    }
  },
  methods: {
    addSkill() {
      this.$validator.validateAll().then((result) => {
        if (result) {
          this.skills.push({skill: this.skill})
          this.skill = '';
        } else {
          console.log('Not valid')
        }
      })
    }
  }
}

I am utilizing code from an example where my v-model in the input is "skill." How can I create a method that correctly saves the last input in the cache? I wish to be able to add a new skill to the array and still see the value persist in the array even after refreshing the page. Is this achievable, and if so, how can it be done? I am completely new to Vue and would appreciate any assistance.

Answer №1

Your issue pertains to localStorage rather than Vue.js. Here's the solution:

export default {
  name: 'Skills',
  data() {
    return {
      skill: '',
      skills: [
        { 'skill': 'Vue.js' },
        { 'skill': 'Frontend Developer' }
      ]
   }
},


  mounted() {
    const skillsList = JSON.parse(localStorage.getItem('skillsList')) || []
    if (skillsList.length > 0) {
      this.skills = skillsList;
      this.skill = skillsList[skillsList.length - 1];
    }
  },
  methods: {
    addSkill() {
      this.$validator.validateAll().then((result) => {
        if (result) {
          this.skills.push({skill: this.skill})
          localStorage.setItem('skillsList', JSON.stringify(this.skills))
          this.skill = '';
        } else {
          console.log('Not valid')
        }
      })
    }
  }
}

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

The issue of javascript Map not updating its state is causing a problem

I've encountered an issue where my components are not re-rendering with the updated state when using a map to store state. const storage = (set, get) => ({ items: new Map(), addItem: (key, item) => { set((state) => state.items ...

Automatically logging in to a website using an AngularJS form

I am struggling with autologin to a website that has an authentication form built with Angular JS. The form structure looks like this: <form name="loginForm" class="login-form ng-pristine ng-invalid ng-invalid-required"> <div class="tight-fo ...

Following the implementation of the YITH ajax navigation filter, my jQuery scripts are no longer functioning as

I'm having trouble with using yith ajax navigation in my theme. Everything works perfectly until I click on an element to filter, at which point my jquery codes stop working. The team at yith suggests: If your product list contains JavaScript cod ...

Having difficulty integrating framer-motion with react-router

I've been working on adding animations and smooth transitions to my app using Framer-motion, but I'm facing some challenges in getting it all to function properly. With react-router 6, my goal is to trigger exit animations on route sub-component ...

Troubleshooting Guide: Resolving Gatsby Develop Issue "Module 'gatsby-cli/lib/reporter' Not Found"

Experiencing an issue with Gatsby. I am encountering the error message Error: Cannot find module 'gatsby-cli/lib/reporter' in the command prompt while running gatsby develop. How can I resolve this problem? Please provide a solution. Error Messa ...

A TypeScript method for accessing deeply nested properties within an object

I'm currently working on a function that utilizes typings to extract values from a nested object. With the help of this post, I managed to set up the typing for two levels successfully. However, when I introduce a third (known) level between the exis ...

How can I use jQuery to separate special characters from letters in a string?

I'm facing an issue with my code related to validation. There is a existing validation in place that restricts users from entering letters and special characters in a textfield. Now, I need to incorporate this validation into my code but I'm uns ...

Exploring the distinctions among library, package, and module in JavaScript

As I dive into learning React, I find myself feeling overwhelmed by the idea of packages. Why can't we simply use a CDN link instead? There's this module that seems to be crucial but still puzzles me. And what exactly is npm and why is it necessa ...

Tips for preventing labels from overlapping in JavaScript

After texturing an image to a sphere in 3D (as shown below), I encountered an issue where the planegeometry labels were overlapping. I am looking for a way to separate these labels using the three.js library. 2 labelBox.prototype.update = function() { ca ...

Is the output of MongoDB's ISODate() function always distinct from that of the Date()

After reviewing the documentation, my understanding was that ISODate simply wrapped the Date constructor. However, I've encountered issues when working with dates very far in the past. For example: new Date(-8640000000000000); ...

The outcome of comparing with Bcrypt is consistently a negative result

bcrypt.compare() is consistently returning false when used in conjunction with this code within the user model. It appears that this issue is specific to bcrypt-nodejs. User.pre('save', function (callback) { this.password = bcrypt.hashSync(thi ...

The onChange event does not function properly on formatted Mui sliders

Having an issue with the Mui styled Slider. The value is not changing smoothly and it seems like the thumb of the slider is not draggable. You can see the issue reproduced here. Thank you in advance. ...

The combination of checkboxes and buttons

Here is the first code snippet: <div class="five columns"> <a class="button small primary right" style="margin-top: 30px;"> Опубликовать выбранное </a> And here is the second code snippet: <td> <p& ...

I could see the Javascript and CSS code manifesting directly onto my HTML page

I've encountered a strange issue with my calendar code where my JavaScript and CSS codes are inexplicably showing up next to the calendar. Does anyone have any insights into why this may be happening? I developed the code in an online HTML/CSS/JS edit ...

Developing a Spring MVC application that sends a JSON response to an AJAX

I encountered a problem with JSON parsing that resulted in a SyntaxError: "JSON.parse: bad escaped character" while handling an AJAX success event. The AJAX code in question is as follows: $("#ajaxform").submit(function(e) { $.ajax({ url : &apo ...

Tips for customizing table cell styling in editable cells with React material table

My code utilizes a material table with editable cells. However, I am encountering a strange style issue when I edit a cell in the table. Please refer to the image below. Can anyone suggest a solution to fix this problem? https://i.sstatic.net/Miiov.png ...

React - manipulating data with state, yay or nay?

My form has two columns - the left column displays a proposed value for the right column. Currently, I retrieve both values from separate API calls and everything is functioning as expected. This is how my code looks at the moment: const dbContact = useD ...

At which location do you configure the applicationIconBadgeNumber?

Can anyone guide me on how to set up the applicationIconBadgeNumber for a React Native / Expo application on both iOS and Android platforms? I am currently using React Native, Visual Studio Code, and Expo. Where should I look to configure this feature? O ...

How can you delay the return of a function until after another asynchronous call has finished executing?

Currently, I am working on implementing route authentication in my project. To achieve this, I have decided to store the authenticated status in a context so that other React components can check whether a user is logged in or not. Below is the relevant co ...

Is there a way for mocha to conduct a recursive search within my `src` directory in order to find a specific

In my npm project, I want to replicate the structure used by Meteor: there is a source file called client.js and its corresponding test file named client.tests.js residing in the src/ directory. The tests should be executed with the npm test command. I am ...