Is it possible to dynamically register models in Vue?

When working inside a Vue-component, I encounter a scenario where I need to create a list with a variable number of entries.

For example, it could look like this:

<form>
<input type="number" value="15" />
<input type="number" value="10" />
<input type="number" value="5" />

<input name="total" :value="summedTotal" /> <!-- (calculated dynamically) -->
</form>

Or it could be something like this:

<form>
<input type="number" value="15" />
<input type="number" value="10" />
<input type="number" value="5" />
<input type="number" value="17" />
<input type="number" value="20" />

<input name="total" :value="summedTotal" /> <!-- (calculated dynamically) -->
</form>

If the number of input fields was fixed, I could have easily solved it using v-model. However, since the number of 'models' is dynamic, I'm seeking a solution that still allows me to use v-model.


Currently, my workaround involves adding an @keypress event, locating the specific input element (document.getElementById('....')), and extracting the value from it. But I need to introduce a delay for this to function properly. While I could opt for using keyup or another event watcher, this approach feels quite makeshift and non-ideal.

The actual code represents an advanced version of this:

<form>
<input 
   type="number" 
   v-for="(entry, index) in list" 
   name="entry.id" 
   value="entry.initial_value"
   :id="'entry-id__' + entry.id" @keypress="calculateSum()" 
/>

<input name="total" :value="summedTotal" /> <!-- (calculated dynamically) -->
</form>

Answer №1

To enable your input fields to update the values in the list, you can utilize a v-model like this:

<input 
   type="number" 
   v-for="(item, index) in list"
   :key="'input-'+item.id"
   name="item.id" 
   v-model="item.initial_value"
   :id="'item-id__' + item.id" 
/>

Whenever a user changes a value, it will directly modify the corresponding value in the list object.

Lastly, retain the last line as follows:

<input name="total" :value="summedTotal" />

where summedTotal is a computed value summing up the values from your list.

If you prefer not to alter the original list, you can create a deep copy first and then use copiedList for your v-model:

data {
  copiedList : JSON.parse(JSON.stringify(this.list))
}

Here's a functional Snippet:

new Vue({
  el: '#app',
  data: {
    list: [{
        id: 1,
        initial_value: 3
      },
      {
        id: 2,
        initial_value: 1
      },
      {
        id: 3,
        initial_value: 7
      },
      {
        id: 4,
        initial_value: 2
      },
    ]
  },
  computed: {
    summedValued() {
      return this.list.reduce((acc, val) => {
        return acc + parseInt(val.initial_value || 0);
      }, 0)
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <div v-for="(item, index) in list" :key="'input-'+item.id">
    ID {{item.id}}: <input type="number" name="item.id" v-model="item.initial_value" :id="'item-id__' + item.id" />
  </div>
  TOTAL :{{summedValued}}

</div>

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

Alter the configuration of a JSON object

I'm currently working on modifying the following JSON text. It has the structure as shown below: { "cabecera": { "tipo_cambio": "", "fecha_emision": "", "total": "" }, "detalle": { "940b130369614bd6b687dc5b41623439": { " ...

Access the extended controller and call the core controller function without directly interacting with the core controller

i have a core controller that contains an array called vm.validationTypes with only 2 objects. I need to add 3 or 4 more objects to this array. to achieve this, i created another controller by extending the core controller: // CustomValidation angular.m ...

Holding off on triggering a jQuery Ajax request until a function returns a value

I'm currently facing an issue where an Ajax request is not waiting for a function call to return before executing. The specific scenario involves calling getSelectedMessages to retrieve checkbox values and then passing these values in an array to the ...

"Troubleshooting: Child Component Not Reflecting Changes in UI Despite Using Angular

My child component is designed to display a table based on a list provided through @Input(). The data is fetched via http, but the UI (child component) does not update unless I hover over the screen. I've seen suggestions about implementing ngOnChange ...

I recently created an application using Vue and I'm exploring options for storing information to use later. Would using js-cookie be a viable solution for this?

After experimenting with Vuex to store user-selected information in my app, I found that the data was lost upon page reload. Switching to Cookies and using js-cookie solved this issue seamlessly. It makes me wonder if there is a downside to relying on cook ...

Altering the DOM directly within the componentDidMount() lifecycle method without needing to use

In ReactJS, I am facing an issue while trying to manipulate the DOM in the componentDidMount() method. The problem lies in the fact that the DOM is not fully rendered at this point, requiring me to use a setTimeout function, which I find undesirable. Upon ...

The concept of a callback function is not applicable within the context of MongoDB in Node.js

I am encountering an issue while validating the existence of an email or username in my MongoDB users collection within Node.js using my User Model. Whenever I attempt to perform this validation, I receive an error stating callback is not a function. This ...

Using a loop in a Vue.js slick slider: easy step-by-step guide

While utilizing vue-slick link https://www.npmjs.com/package/vue-slick within a bootstrap modal, I encountered an issue when using a v-for loop to iterate through the items. The problem can be seen in this example: https://i.sstatic.net/PhJCE.jpg. Below i ...

The Autofocus feature in HTML5 is malfunctioning in Internet Explorer 9

I am currently working on a project for IE9, and I am having trouble with the HTML5 autofocus keyword not functioning as expected. Specifically, the autofocus feature that puts the cursor in the specified input field is not working in IE9 (and I am forced ...

Error thrown in JavaScript when calculating the distance

I am currently working on calculating distances between two points, but I keep getting an error that says Uncaught TypeError: a.lat is not a function. function MapLocations() { var i = 0; var infoWindow = new google.map ...

Implementing nested CSS styles with jQuery - a step-by-step guide!

In my stylesheet.css file, I have the following code: .vertical-navigation .navbar-default .navbar-nav > li > a:hover { background-image: url(../images/sticcky_nav_hover.png) } .vertical-navigation .navbar-default .navbar-nav > li > a.navf ...

The element 'flat' is not found within the specified type

My challenge involves utilizing the flat() method in a TypeScript script. In my tsconfig.json file, I have set the target to es2017 and defined an interface for the input variable. However, I keep encountering this error message: Property 'flat' ...

Designing the MongoDb schema for creating user accounts with subscription plans

To meet the Account creation requirements, I must design a schema that spans three steps. Step 1 involves capturing Email-id along with password and password confirmation. For Step 2, users are prompted to select a subscription plan - be it basic, standa ...

Navigating the balance between local state and global state in React components with Flux architecture

It can be unclear at times: where should I store the state of a React view, such as the active tab, selected option, toggler value, or a flag indicating input validation? There are actually two options to consider: Dispatch an action and store the data ...

I'm struggling to find a way to showcase my JSON data in HTML. Update: I have a clear vision of how I want it to look, but I'm struggling to display it in any format other than raw JSON

I've been trying to figure this out for hours, scouring every resource I can find, but I'm stuck. I've left the API URL in there, so feel free to take a look (it's public). If my message doesn't make sense due to exhaustion, please ...

Looking for a way to assign the (file path to kml) to a variable in your code while utilizing geoxml3?

Is there a way to store the KML file in a variable before parsing it with myParser? Check out this link for more information: https://github.com/geocodezip/geoxml3 var myParser = new geoXML3.parser({map: map}); myParser.parse('/path/to/data.kml' ...

Get image data from Next.JS API and show it in the web browser

I am looking to utilize my own next.js endpoints to request an image that I can then embed into my website. Currently, the issue I am facing is that the image seems to be immediately downloaded and does not display in the browser window. import type { Next ...

Having trouble with the submit event listener in vanilla JavaScript

Looking to post a form via AJAX without jQuery involved. The form has an action of "/generate/transaction" and method="POST". After submitting the form, the URL changes to 'localhost/generate/transaction', which is causing an issue. It seems like ...

Transforming class components to utilize hooks (storing state within an if statement)

I am facing a challenge with some old code that is structured within a class and I need to convert it to hooks. I have successfully converted most of the code, except for one instance where state is declared inside an if statement. The other conversions in ...

Issue with Vue styles not loading in production when using Rails/Webpacker

I recently upgraded my Rails app to use webpacker 4.x and encountered a strange issue. While everything works fine in development, the styles of Vue single file components are not rendered in production. Surprisingly, the JavaScript works perfectly, and ev ...