storing prepopulated form fields in vue

As I work on a complex form, my goal is to ensure that users do not lose their data when reloading the browser. Thankfully, modern browsers automatically refill data on reloads - even inputs with v-model retain their values during beforeMount. However, they lose this data once they reach mounted, as they are filled with empty data from the model. I am considering filling the model on beforeMounted with data extracted from the DOM. Is there a way to get the reference of a v-model linked to the object in the DOM? Alternatively, what other methods would you recommend for achieving this?

Answer №1

Imagine you're setting up a new user, which means you already have the user model defined within your component like this:

data () {
  return {
    user: {
      email: '',
      password: ''
    }
  }
}

Next, you have an input element structured as

<input type="email" v-model.lazy="user.email" />
(pay attention to the lazy modifier for better performance).

To further enhance this setup, you can add a watcher for the user model that saves its values in sessionStorage (or localStorage if preferred). Refer to the documentation here: https://v2.vuejs.org/v2/guide/computed.html#Watchers

In your component, include:

watch: {
  user (newValues, oldValues) {
    window.sessionStorage.setItem('userData', JSON.stringify(newValues))
  }
}

Before mounting the component, ensure you load the stored values with:

created () { // created hook
  let userData = window.sessionStorage.getItem('userData')

  if (userData) {
    try {
      userData = JSON.parse(userData)

      // assign values to the model
      this.user.email = userData.email
      this.user.password = userData.password
    } catch (err) {
      // handle invalid json string
    }
  }
}

Answer №2

Utilizing the inherent capabilities of the browser is my primary focus here, as I can integrate this simple technique into a universal mixin or plugin without being tied to any particular data structure. By storing all necessary information in the DOM and updating it post mounted event, I ensure seamless functionality.

export default {
    beforeMount() {
        document.querySelectorAll('input').forEach((el) => {
            if (el.value) {
                el.setAttribute('data-prefill', el.value)
            }
        })
    },
    mounted() {
        this.$el.querySelectorAll('[data-prefill]').forEach((el) => {
            this.$nextTick(function() {
                el.value = el.getAttribute('data-prefill')
                el.dispatchEvent(new Event('change'))
                el.dispatchEvent(new Event('input'))
            })
        })
    }

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

New feature in Safari extension: transferring window object from inject script to global page

Is it possible to transfer the window object from an injected script to a global.html page? I am attempting to pass the window object as part of an object to the global page. However, when I try to dispatch the message from the "load" listener function, i ...

Sharing Props between React.js Components

After spending two days searching online, I am still struggling to pass an index from one element to a sibling element in order to display it. All I have been able to achieve so far is showing data inside every div, but I really want to only do it on the c ...

Divs expanding below content in IE on a particular server

Currently, I am facing an issue with a JavaScript div that expands correctly over other content in most situations but goes under the content in one specific scenario. I am unsure about where to begin debugging this problem. To provide some context, the d ...

Determine the vertical dimension of a child division once it has been integrated into an HTML document

My goal is to create a website with multiple pages without having to recreate the toolbar for each page. To achieve this, I have created a separate HTML file and CSS file specifically for the toolbar. On each page, I simply import the toolbar using the fo ...

Utilizing Thymeleaf With JavaScript in Spring Boot: A Comprehensive Guide

Within my Spring Boot project, I am attempting to utilize Thymeleaf for injecting data into a JavaScript file that undergoes preprocessing with babel via WebPack. The Thymeleaf setup is outlined as follows: @Bean public SpringTemplateEngine templateEngine ...

Meteor - Utilizing If Statements in HTML Documents

Currently, I am utilizing an FS Collection named "MyUploads" for storing user-uploaded files. Within the HTML structure, there exists a submit button that needs to be displayed conditionally. The question at hand is: how can I create an if statement so tha ...

What is the most effective method for flipping a THREE.Sprite in r84?

After updating my game engine from r69 to r84, I encountered a few issues. One of them is related to flipping sprites. In the past, I could easily flip sprites using the following code: sprite.scale.x = -1; Unfortunately, this method no longer works in ...

What is the process for creating an animation with a filter or toggle effect?

I am eager to create an interactive animation for my search engine on my website, but I'm struggling with where to begin. Here is the relevant HTML snippet: <div id="companyRoster" class="companyRoster container"> <div class="row mb-2"& ...

Tips for pinpointing a particular item within a JSON document

I am struggling with how to manipulate my JSON file using JavaScript. Each object in the array is associated with an ID, and I want to be able to target specific objects based on their position in the array. For example, how can I append object[1] from arr ...

Allowing multiple requests to be executed simultaneously in Express.js without causing any blocking issues

I am facing an issue with my Express.js website while handling post requests. The server hangs when a request triggers a query that takes several minutes to execute and respond from the database. Below is the code structure I use for database queries: Se ...

Consistently receiving the identical result even when the checkbox remains unselected

Displaying a Checkbox Input <input id="idCheckbox" name="check" type="checkbox" value="AllValue" style="width: auto; height: auto; font-weight: bolder;" data-bind="checked: idCheckbox" /> The checkbox input will always have the value "AllValue ...

reloading a webpage while keeping the current tab's URL selected

I want to incorporate a feature I saw on the jQuery website at http://jqueryui.com/support/. When a specific tab is pressed, its contents should open. However, when the page is refreshed, the same tab should remain open. I'm trying to implement this i ...

Using window.open in Google Chrome results in multiple tabs being opened instead of just one

I have a dynamic input field with a search button. Initially, only one tab is opened when I click the button. But after saving and clicking it again, multiple tabs open for the same URL. The number of tabs is equal to the number of dynamic input fields cre ...

The issue with jqTransform not displaying the select box value on a hidden contact form

Could really use some assistance here and apologize if it's a hassle: Link to contact form To view the contact form, simply click the "Contact" button in the top left corner. The jqTransform jQuery plugin is being used to style it. Initially, it&apo ...

Trouble rotating camera in THREE.JS?

How can I adjust my camera to look behind, with the center of the pong table being at x=0,z=0? I've tried changing the camera.lookAt settings but haven't had success. You can see the current camera view here. scene = new THREE.Scene(); scene ...

Angular: Observing changes in the store and sending a message from a Service component to another component once the Service has finished specific tasks

Within our codebase, we introduce two classes known as GetDataAsyncService. This service is designed to wait for a change in the store before executing the block of code contained within it. By utilizing observables and subscribing to data changes with t ...

Challenges with handling Ajax responses in Ruby on Rails

I'm currently facing an issue with the Ajax response in my Rails application, and I'm unsure of how to troubleshoot it. Here is the code that is functioning correctly: View <div id="<%= dom_id(comment) %>_count"> <%= Like.wh ...

In my attempt to assess the correlation between value 1 and a value in the preceding object, I am utilizing the *ngFor directive

Attempting to compare 2 entries in an *ngFor loop. The code should compare the value at the current object to a value at the previous object. <ng-container *ngFor="let item of s_1.comments[0]; index as b"> <article class="message i ...

In Safari, Angular 6 fails to display data points when a component is routed to the d3/event-drops

After creating a test app to replicate the current issue, I have come across an interesting problem. Here is the link to the codebase: https://github.com/mohammadfarooqi/event-drops-d3-test-app. You can also view a sample demo deployed (recommended in saf ...

What techniques can be employed to create a fully operational web application using AngularJS?

I have taken on the challenge of understanding AngularJS by creating a webapp. Within my Eclipse environment, I am working with 4 files: main.js, index.html, view1.js, and view2.html. Currently, I can get index.html to load when Tomcat is running. Embedd ...