What is the best way to prepopulate form values in a Vue object?

Sharing my code snippet:

HTML:

<div id="user-panel">
     <div class="text-center">
       {{ fillItem }}
     </div>     

          <form method="POST" action="http://site5/user_account/experiences/17" accept-charset="UTF-8" v-on:submit.prevent="updateItem(17)">

            <input name="_method" type="hidden" value="PATCH">
            <!-- Employer Field -->
            <div class="form-group col-sm-6">
              <label for="employer">Employer:</label>
              <input class="form-control" v-model="fillItem.employer" name="employer" type="text" value="Some Emplyer" id="employer">
            </div>

            <!-- Designation Field -->
            <div class="form-group col-sm-6">
              <label for="designation">Designation:</label>
              <input class="form-control" v-model="fillItem.designation" name="designation" type="text" value="some designation" id="designation">
            </div>
            <!-- Submit Field -->
            <div class="form-group col-sm-12">
              <input class="btn btn-primary" type="submit" value="Save">
            </div>
          </form>
</div>

Javascript:

<div id="user-panel">
     <div class="text-center">
       {{ fillItem }}
     </div>     

          <form method="POST" action="http://site5/user_account/experiences/17" accept-charset="UTF-8" v-on:submit.prevent="updateItem(17)">

            <input name="_method" type="hidden" value="PATCH">
            <!-- Employer Field -->
            <div class="form-group col-sm-6">
              <label for="employer">Employer:</label>
              <input class="form-control" v-model="fillItem.employer" name="employer" type="text" value="Some Emplyer" id="employer">
            </div>

            <!-- Designation Field -->
            <div class="form-group col-sm-6">
              <label for="designation">Designation:</label>
              <input class="form-control" v-model="fillItem.designation" name="designation" type="text" value="some designation" id="designation">
            </div>
            <!-- Submit Field -->
            <div class="form-group col-sm-12">
              <input class="btn btn-primary" type="submit" value="Save">
            </div>
          </form>
</div>

Visit this jsfiddle link for a demo.

My goal is to populate vue object with default form field values.

Despite having default values in the form fields, vue renders them blank. How can I retrieve the default form values in vue considering that the values are dynamic, and the JavaScript code resides in a special.js file?

Answer №1

In the documentation for v-model on the Vue website, it explains that:

<input v-model='something'>

is essentially a shortcut for

<input :value='something' @input="value => { something = value }">

This means that when you assign a value to the input, Vue will update the value using the data from the Vue instance. Therefore, you cannot initially set the default value of a form field in Vue using the value attribute of the input tag.

To initialize the value, you can set it directly in the Vue instance when you initialize it, or modify the Vue object in a callback function to dynamically access default values.

I hope this provides some assistance.

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

I am facing an issue with body-parser not properly processing my request in express.js

Utilizing the Controller in my project. Snippet from app.js: var express = require('express'); var app = express(); const routes = require('./Routes/route'); const bodyParser = require('body-parser'); app.use('/', ...

Trouble with refreshing button after resolving routes in Angular UI Router

My Angular UI router is giving me trouble. When I navigate to the state below, everything works smoothly. However, if I refresh the page, the resolve function retrieves the data, injects it into the controller, but the view does not load. Essentially, th ...

Retrieving a parameter in NextJS from the request.body when it is not found

In the API code for my nextJS, I have implemented the following logic: export default async function handler(request, response) { if (request.method === "POST") { const type = request.body.type ?? 'body type' const ...

Tips for customizing the timing of a Bootstrap modal's opening delay?

I have integrated gem "bootstrap-sass", "~> 2.3.0.0", which indicates that I am utilizing Bootstrap 2. Detailed information on the modal can be found here. The code for my custom modal looks like this: #Modal.modal.hide.fade{"aria-hidden" => "true" ...

Contrasting the variance between binding through the [] syntax and abstaining

There is a unique custom my-table element that has its row property bound to the host component. There are two different ways in which HTML can be inserted: <my-table [rows]="displayEntriesCount"></my-table> and alternatively: <my-table r ...

I keep encountering the issue where I receive the message "Unable to access property 'innerText' of an undefined element" when running the Array forEach function. This problem seems to be happening within the HTMLInputElement section of the code

I am facing an issue where the error occurs because "cardTxt" is not recognized as a string. I verified this using typeof syntax, but I'm unable to understand why it can't be a string. This code snippet includes the use of bootstrap for styling. ...

The authentication protocol, Next Auth, consistently provides a 200 status response for the signIn function

I ran into a challenge while building my custom login page using Next Auth. The issue arises when I try to handle incorrect login data. If the login credentials are correct, I am able to successfully send JWT and redirect to /dashboard. However, when the l ...

Using JavaScript, retrieve the current time from the client's device with a timer counter

I'm having trouble with my website. I created a countdown timer using PHP code and JS. The issue arises when I try to calculate the real end time based on "end time from DB - server current time + client time" and then echo it. Instead of getting the ...

Encountering an issue with launching npm serve on MacOS while using IntelliJ Ultimate for a Vue.js project

I can't seem to get npm serve to start in the Run/Debug Configuration within IntelliJ. However, when I run it separately in the Terminal within IntelliJ or on the regular console, it works just fine. Any idea what's causing this and how to fix ...

How can I generate an incidence array using randomly generated array elements?

Considering the following: var dataset = [ {X: 0, Y: 0, ApiKey: "Something"}, {X: 100, Y: 0, ApiKey: "Something"}, {X: 1500, Y: 200, ApiKey: "Something"}, {X: 1600, Y: 850, ApiKey: "Something"}, {X: 0, Y: 750, ApiKey: "Something"}, {X: 0 ...

Leveraging the node CLI tool as a library for trimming MP3 files (trimp3

I recently came across a fantastic library that I am interested in using for my nodejs project: https://github.com/kyr0/trimp3 The only issue is that it functions as a cli tool, and I would like to integrate it seamlessly into my codebase as a library. D ...

A guide to fetching a JSON Object from a URL using Node.js and Express

As a newcomer to Node.js and Express, I am venturing into my first real project with these technologies. In this simple Node.js/Express project, my goal is to retrieve a JSON object from a URL. Additionally, I plan to create another URL that shows HTML co ...

Issue with the camera functionality in phonegap 3.3.0 API on IOS platform

I am currently in the process of developing an application for iPad that will allow users to capture and store photos. I have encountered some difficulties while using the PhoneGap camera API library, as my code is not generating any errors which makes i ...

Disable toolbar focus in TinyMCE

Is there a method to prevent the appearance of the white square known as "Focus to toolbar" in TinyMCE? Clarification: Upon pressing Alt+F10 in TinyMCE, a white square is outlined around a button on the toolbar. This allows navigation among toolbar butto ...

Automated logout feature will be enabled if no user interaction is detected, prompting a notification dialog box

Here is my working script that I found on this site. After a period of idle time, an alert message will pop up and direct the user to a specific page. However, instead of just the alert message, I would like to implement a dialog box where the user can ch ...

Error: Express JS custom module cannot be located in the root directory's modules folder

The file structure of my express js app resembles thishttps://i.sstatic.net/57NIQ.png I'm attempting to load a modules folder from the root directory. routes/users.js var express = require('express'); var router = express.Router(); var md ...

Having trouble parsing an array from req.body using Node.js Express

I am currently facing an issue while trying to retrieve an array from a JSON request using Postman. In my Node.js application, I am able to read all values from req.body except for the array. When attempting to access the array, I only receive the first va ...

How can I add multiple filters to a Kendo Grid?

Is there a way to include two separate filter fields for date filtering in Kendo Grid UI? Currently, the method I am using only allows for one date filter to be displayed. filterable: { ui: function (element: any) { element.ken ...

Is there an advantage to pre-compiling jade templates for production in an express environment?

Is it advantageous to have a middleware that pre-compiles all .jade views for production use, or does this happen automatically when NODE_ENV is set to 'production'? I am investigating ways to accelerate jade rendering for production purposes. ...

Modify the background color of a div by selecting a hex code from a dropdown menu

Is there a way to utilize jQuery in order to alter the background of a <div> by choosing the HEX code from a separate dropdown menu? HTML <select id="target"> <option value="#c2c2c2">Grey</option> <option value="blue">Bl ...