Using Vue.js to bind data in two directions by using an object with v-for

I can't seem to get input data properly bound to object properties. When I try to iterate through an object to create input fields based on its attributes, the v-model data binding doesn't seem to be working as expected. Even with the code below, my console log remains empty:

<div id="app">
<div v-for='value, key in fields'>
    {{ key }}: <input v-model='value'>
</div>
<button @click="add">Add</button>
</div>

<script>

new Vue({
el: '#app',
data: {
    fields: {
        id: 123,
        name: 'abc'
    }
},
methods: {
    add: function(){
          console.log('id: ' + this.fields.id)
          console.log('name: ' + this.fields.name)
    }
}
})

</script>

Answer №1

If you want to access the fields[key] with v-model, using value in its place will not function properly since it is a local variable within the v-for loop.

<div id="app">
  <div v-for='(value, key) in fields'>
    {{ key }}: <input v-model="fields[key]">
  </div>
  <button @click="add">Add</button>
</div>

To see a live demonstration, click on this link.

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

ng-repeat not functioning properly with custom tabs

Everything was working perfectly until I added ng-repeat to the content <ul> <li ng-class="{active:tab===1}"> <a href ng-click="tab = tab==1 ? a : 1">Tab1</a> </li> <l ...

Utilize useMediaQuery for identifying various breakpoints in your design

Currently, I am working on detecting multiple breakpoints in my application to ensure dynamic column generation on a Grid. Although I have managed to accomplish this task, the code appears somewhat repetitive. Is there a method through which I can simpli ...

utilizing the data provided by a user in the "prompt" window within my HTML code

Looking to utilize user input from the prompt window. This is my custom JavaScript form: var answer; function load() { answer=prompt("what is your name?", "Write your name here"); return answer; } function hideNsee() { var HNS = docume ...

Retrieve a div element using Ajax from the result of an If statement

I need to extract a specific div from the data returned by an if statement that is formatted as HTML, and then display it within another div. I have been attempting to achieve this using the code below, but so far it has not been successful... Here is my ...

Directing a controller assignment in AngularJS 1.2 via a directive

Transitioning from angularJS 1.0 to 1.2 has presented a challenge for me when it comes to assigning a controller to a directive with a distinct scope, without explicitly defining the controller in my HTML using ng-controller. Let's look at this scena ...

Enhancing the visual display of a webpage using AngularJS

Hello there! I'm currently working on enhancing an angular 1.6 app and have encountered a dilemma that needs solving. Let me provide some context: The page in question is a lengthy form consisting of thirty questions. The client-side logic includes nu ...

Save information for each session with a set expiration time

Currently, I am working on a mobile application using Angular (specifically Ionic 5) and I am in need of a solution to maintain session data for my users throughout their workflow. Initially, I thought about utilizing the sessionStorage feature for this p ...

Error message encountered in Rails Webpacker: "Uncaught TypeError: $(...).tooltip is not recognized as a function

I am working on a Rails 6 application where I compile assets using Webpack 4.39.1 with the help of the Webpacker gem. In my webpack configuration file (config/webpack/environment.js), I have included JQuery 3.4.1 and Popper.js as part of the ProvidePlugin ...

Does type conversion have a specific ranking of preference?

When working with JavaScript, it's important to note that the language automatically converts types when necessary. For instance, if you have an expression like "8" * "3", JavaScript will convert the strings to numbers and calculate the result as 24. ...

The 3-way data binding in angularFire does not update a function

My issue involves a firebaseObject (MyFirebaseService.getCurrentUser()) being bound to $scope.user. Once successfully bound, I iterate through the object to check if it contains an "associatedCourseId" equal to a specific value ($stateParams.id). If it doe ...

creating a while loop in node.js

In C#, the following code would be used: double progress = 0; while (progress < 100) { var result = await PerformAsync(); progress = result.Progress; await Task.Delay(); } This concise piece of code spans just 7 lines. Now, how can we ...

What mistakes am I making in my usage of React hooks in this situation?

As part of my journey through the FullstackOpen course at the University of Helsinki, I am working on creating a simple Phonebook application. In troubleshooting my code, I've noticed that my 'filterBy' state is consistently one step behind, ...

Angular 2 Encounter Error When Trying to Access Undefined Property in a Function

Element: import { Component, OnInit } from '@angular/core'; import { HttpClient } from '@angular/common/http'; @Component({ selector: 'app-ore-table', templateUrl: './ore-table.component.html', styleUrls: [&a ...

The error message states: "TypeError: a.map is not a function"

I recently deployed my React JS app on Heroku and encountered some issues with the routing. While everything worked smoothly on my local host, I faced errors after fixing the routing problem that I couldn't resolve. Despite extensive research, I haven ...

Click the button on your mobile device to open the already installed Android app

After creating a small Android app using jQuery Mobile, I incorporated a button to open another native Android app. Is it feasible for the jQuery Mobile app button to load/open an already installed and functioning native Android app upon click? I would gr ...

Navigating the division between presentational and container components in React/Redux

Here is a basic outline of my current setup: container.js: import Presentation from './Presentation'; import { connect } from 'react-redux'; export default connect( ({ someState}) => ({ ...someState }), (dispatch) => { ...

ng-options encounters duplicate data when using group by in Internet Explorer

The dropdown menu that lists states works fine in Google Chrome, but duplicates groups in Internet Explorer. In Chrome, there are 2 groups, but in IE there are 4. How can I fix this issue in IE as well? Thank you. Here is the code snippet: <!DOCTYPE h ...

The Ajax function fails to trigger during the first load of the page

Note: Kindly refer to the update at the end of this question before proceeding. The problem described is specific to IE 11 and emerged after a recent Windows update. Following the installation of 5 updates, including one for IE, I removed the latter hopin ...

Transform a string into a JSON entity

Can JavaScript be used to convert a string such as this: "Product : Bike , 2005 : $12000,2006 : $13000,2007 : $14000,2008 : $15000" into a JSON object like the one below: { "Product":"Bike", "2005" : $12000, "2006" : $13000, "2007" : $14 ...

Module not discovered by nodeJS within the current directory

In my node application, I am trying to incorporate a module called dishRouter. The file structure looks like this :- Structure The dishRouter is exported from Dishes/index.js and imported into my app.js using the following code: var dishRouter = re ...