What is the best way to store user input in local storage using Vue.js?

Following the official Vue.js site, I have been trying to implement Framework 7. However, when using an input field, [object InputEvent] is displayed both when typing text and attempting to save it.

Is there a way to store a name in local storage and have it appear back in the input field?

Note that v-model does not work in Framework 7.

<f7-list form>
    <f7-list-input
      label="Username"
      name="username"
      placeholder="Username"
      type="text"
      v-bind:value="name"
      required validate
      pattern="[3-9a-zA-Zа-яА-ЯёЁ]+"
      @input="persist"
    />
  </f7-list>

<script>
export default {
data() {
    return{
        name: '',
        }
    },
mounted() {
  if (localStorage.name) {
    this.name = localStorage.name;
   }
},
methods: {
        persist(){
            this.name = $event.target.value;
            localStorage.name = this.name;
         }
}
};
</script>

Check out the output in the input field

Answer №1

Enhanced code by implementing correct local storage methods and removing a line that was causing the issue

Make the following substitution:

name=$event.target.value;

to

this.name = $event.target.value;

Below is the revised code with updated techniques and optimized structure.

<f7-list form>
      <f7-list-input
        label="Username"
        name="username"
        placeholder="Username"
        type="text"
        v-bind:value="name"
        required validate
        pattern="[3-9a-zA-Zа-яА-ЯёЁ]+"
        @input="persist"
      />
    </f7-list>

  <script>
  export default {
  data() {
    return{
        name: '',
      }
    },
  mounted() {
    if (localStorage.name) {
      this.name = localStorage.getItem('name')
    }
  },

   methods: {
             persist(){
       // Store name in local storage here using setItem is recommended 
       // but even without that change, your code should function properly.
                localStorage.setItem('name', $event.target.value)
          }
      }
      };
  </script>

Answer №2

Put it in simple terms :

Save the 'name' data to local storage

Retrieve the 'name' data from local storage

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

(React) Error: Unable to access property 'this' as it is set to undefined while trying to utilize refs

When using a ref in React to refer to an input field, I encountered an error: "Uncaught TypeError: Cannot read property 'this' of undefined". Despite having defined the ref, React seems unable to locate it in my code. What could be causing this i ...

Issue with rendering in sandbox environment versus localhost

Here's a dilemma I'm facing - I have some HTML code on my localhost that looks like this: <div> <p>Go to: <a href="www.foobar.com">here</a></p> </div> On localhost, the output is "Go to: here" with 'he ...

Encountering an issue with undefined property 'path' while attempting to upload an image on the frontend in React

I have encountered an issue while trying to upload an image on the frontend. The error message displayed is: message: "Cannot read property 'path' of undefined" status: "fail" When I log req.file on the backend and attempt to ...

Chorme is throwing a CSRF token mismatch error when working with Laravel API Sanctum

Having an issue with my Vue app and backend Laravel setup. I am using SPA Authentication for authentication. Everything works fine in localhost, but when I deployed it to the server, there are some issues. After sending a login request to sanctum/csrf-co ...

The function e.preventDefault() appears to be ineffective when applied to both the submit button and anchor tag within an

In my ASP.Net Core MVC App View <form> <div class="container"> <div class="row"> <div class="col-md-offset-2 col-md-4"> <div class="form-group"> <input type="text" class="form-contr ...

Displaying Data in React Table from JavaScript Object

I'm working on a React component that will display a table of data from a JavaScript object called pixarMovies. The initial state is set with this object. My goal is to sort the movies chronologically by date and render them in a table format (refer t ...

The Application Insights Javascript trackException function is giving an error message that states: "Method Failed: 'Unknown'"

I've been testing out AppInsights and implementing the code below: (Encountering a 500 error on fetch) private callMethod(): void { this._callMethodInternal(); } private async _callMethodInternal(): Promise<void> { try { await fetch("h ...

What is the correct way to accurately determine the width of a block being displayed with the flex-direction:column property?

For instance: HTML console.log($('.container').width()); // 600px as we defined in css. console.log($('.list').width()); // 600px console.log($('.box').eq('-1').position().left + $('.box').outerWidth( ...

Utilizing Laravel to Retrieve Information from an API

I am currently working with a database table that requires continuous updating. game_id | end_time My challenge now is figuring out how to create a job that will run based on the end_time. This job will need to retrieve data from a third-party API, and i ...

Using two modal popups while passing an identifier

UPDATE: In my investigation, I discovered that a plain input tag without MVC RAZOR works as expected: <input type="text" class="hiddenid2" /> //WORKED However, when using the following code, it does not work: @Html.Editor("id", "", new { htmlAtt ...

The jQuery selector fails to refresh after the dynamic insertion of new elements

My selector is: $('section#attendance input:last') However, I add another input to section#attendance. I want the selector to target that new element since it should select the last element due to :last. However, for unknown reasons, it does no ...

What is the best way to retrieve information from an API and save it in an array within a MongoDB schema?

My current challenge involves querying an API in node.js, storing the obtained data in an array, and then pushing that array to a MongoDB schema. However, I am encountering difficulties as I am receiving an 'unhandledpromiserejection' warning err ...

Unexpected symbols appearing in image tag after AJAX response

I'm currently grappling with an issue related to an AJAX request I am working on (I am quite new to the world of AJAX). I have set up an API and my goal is to fetch a PNG image using an Authorization header that requires a token supplied by me (which ...

I utilized Bootstrap to validate the form, however, despite the validation, the form is still able to be submitted. What steps can I take to

I have implemented form validation using Bootstrap's 'needs-validation'. However, I am facing an issue where the form still gets submitted even when the validation fails. What I want is for the form submission to be prevented if the validati ...

How can one extract dates from a range using mongoose?

Currently, I am working on a rental app project. One of the key functionalities I am trying to implement is the ability to determine the availability of cars between two specified dates, including those dates themselves. Within the database, I have two mai ...

Understanding information in Backbone.js

I have multiple backbone models with nested sub-models. Here's how I've approached the solution: Models.Base = Backbone.Model.extend ({ relatedModels: {}, /** * Parses data based on the list of related models. * * @since ...

Effortlessly create a seamless transition in background color opacity once the base image has finished

I've set up a div with a sleek black background. Upon page load, I trigger an API request for an image, which is then displayed in a secondary div positioned behind the main one. After this, I aim to smoothly transition the overlaying div's opaci ...

Interact with multidimensional arrays using Vue JS

Is there a way to access properties within objects nested inside multidimensional arrays when using v-for with VueJS? var arr =[{"fruit": {"fruitName": "apple"}, "vegetable":[{"vegetableName": "carrot" }]}]; I am attempting to display it in the following ...

Choose a drop-down menu with a div element to be clicked on using Puppeteer

Issue Description: Currently encountering a problem with a dropdown created using material select. The dropdown is populated through an API, and when selected, ul > li's are also populated in the DOM. Approaches Tried: An attempt was made to res ...

In TypeScript version 2.4.1, the fontWeight property encounters an error where a value of type 'number' cannot be assigned to the types of '"inherit", 400'

When attempting to set the fontWeight property in TypeScript, I encounter the following error: Types of property 'test' are incompatible. Type '{ fontWeight: number; }' is not assignable to type 'Partial<CSSProperties>&a ...