Guide on setting a v-model within a v-for loop (using an example from Bootstrap Vue)

Currently, I am utilizing vue-bootstrap for creating input fields using a v-for directive. The objective is quite similar to the example provided in this link. However, I am encountering some difficulties in obtaining the data collected from these inputs into a v-model directive.

One possible approach would be manually assigning each field and mapping it to a v-model for my object. However, if there exists a more efficient solution to tackle this issue, I would greatly appreciate any guidance on this matter.

The code snippet below is essentially copied from the examples page but with my unsuccessful modifications (along with comments):

<template>
  <b-container fluid>
    <code>{{result}}</code>
    <b-row class="my-1" v-for="type in types" :key="type">
      <b-col sm="3">
        <label :for="`type-${type}`">Type {{ type }}:</label>
      </b-col>
      <b-col sm="9">
        <!-- My modification to the v-model part -->
        <b-form-input :id="`type-${type}`" :type="type" :v-model="`result.${type}`"></b-form-input>
      </b-col>
      <!-- Additional "v-model" added corresponding to the previous line of code -->
      <p>{{`result.${type}`}}</p>
    </b-row>
  </b-container>
</template>

<script>
  export default {
    data() {
      return {
        // Defining the result object to store data as expected structure shown below:
        /*
result: {
text: "the text",
password: "the password" 
...
...
}
        */
        result: {},
        types: [
          'text',
          'password',
          'email',
          'number',
          'url',
          'tel',
          'date',
          `time`,
          'range',
          'color'
        ]
      }
    }
  }
</script>

If anyone could shed light on where I might be going wrong, it would be greatly appreciated. I have attempted to search for documentation related to the `"type-${type}"` in the v-for statement, but unfortunately, I was unable to locate relevant information on this topic.

Answer №1

Start by setting up result like this:

result: {
  text: '',
  password:, '',
  email: '',
  number: '',
  url: '',
  tel: '',
  date: '',
  time: '',
  range: '',
  color: ''
}

When using v-model in your template, make sure to access keys with [] instead of ., for example use result[type] instead of result.${type}.

Remember that v-model is a directive on its own, so you do not need to include v-bind(:) when using it:

<b-form-input :id="`type-${type}`" :type="type" v-model="result[type]">
</b-form-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

My React setup is causing some problems that I need to address

React is not my strong suit, but I need to test a React application. The issue arises when attempting to run the server using gulp nodemon, resulting in numerous errors. It seems that the application is built on an outdated version of React and some libra ...

Improve performance by debouncing computed properties and getters in Vue

I'm having trouble getting debounce to work with computed properties and Vuex getters. The debounced functions are always returning undefined. Check out this JSFiddle for an example HTML: <div id="app"> <input v-model="text"> <di ...

What is the best way to ensure that each service call to my controller is completed before proceeding to the next one within a loop in Angular?

Calling an Angular service can be done like this: this.webService.add(id) .subscribe(result => { // perform required actions }, error => { // handle errors }); // Service Definition add(id: number): Observable < any > { retu ...

Mastering the ng-submit directive for AngularJS

Having an issue with my form that submits a location to Google's Geocoder and updates the map with the lat/long. When using ng-click on the icon, it requires double clicking to work properly. And when using ng-submit on the form, it appends to the URL ...

Tips for adjusting the size of a drawing on an HTML 5 canvas within a personalized Polymer component

In my custom Polymer element, I am looking to dynamically resize an html5 canvas when the window resize event occurs. Despite trying to utilize the window.onresize event, I encountered difficulties with accessing canvas functions. One of the functionalit ...

Learn the process of eliminating a class utilizing this JavaScript function

This script is designed to identify and manipulate elements with the class menu-option-set. When an element within this class is clicked, it adds the class "selected" to that specific element while removing it from all others in the list. My goal is to en ...

jquery is showing up in the browserify bundle.js file, however, it is not functioning properly

Currently, I am trying to follow a brief tutorial on how to use Browserify. Despite following the instructions precisely, jQuery seems to not be working properly when bundled. Specifically, the button element in my app.js code is not appended to the body. ...

Understanding Java and JavaScript variables within a JSP webpage

I am currently working on populating a pie chart from Google with data fetched from my database. Although I have successfully retrieved the desired results in my result set, I am facing challenges in converting my Java variables into JavaScript variables ...

Tips for dynamically changing the body class based on the page in a remix

I am trying to set parameters for the body class in root.jsx, which will change based on the page being viewed. I want to assign different values to the class in each route - for example, in _index it should be "company homepage", and in the restaurants ro ...

Utilizing PHP to dynamically generate href links based on radio button selection in real-time interaction with JavaScript

Currently, I am utilizing the MVC framework within Codeigniter and I have a view that contains a link. It's important to mention that the href value is generated by calling a PHP function which takes 'auth/mylogin' as a parameter: <a hre ...

When the mouse leaves, the background image will revert back to its original setting

https://i.stack.imgur.com/Ojd0Q.pngI need assistance in reverting a div's background image back to its default state using the onmouseleave method. Below is the HTML and JS code I have been working on: <script type="text/javascript"> functi ...

Solution to trigger CSS :hover to refresh following a transition (such as expanding a menu)

While there are existing discussions on this topic, I am presenting my query for two specific reasons: It introduces a potential alternative solution The demo code could be helpful to individuals looking to emulate a menu Following a CSS transition, the ...

An error occurs when attempting to redirect with getServerSideProps

When I am logged in, I want to redirect to the /chat page using auth0 for authentication. The error seems to be related to returning an empty string for props, but it does not impact the website as redirection works correctly. The main issue here is the in ...

For the past two days, there has been an ongoing issue that I just can't seem to figure out when running npm start

After multiple failed attempts, I have exhausted all troubleshooting steps including executing npm clear cache --force, deleting node_modules/ and package-lock.json, followed by running npm install, npm build, and eventually npm run dev. The errors encoun ...

Using Array.push within a promise chain can produce unexpected results

I have developed a method that is supposed to retrieve a list of devices connected to the network that the client has access to. export const connectedDevicesCore = (vpnId: string, vpnAuthToken: string) => Service.listVPNConnectionsCore ...

Utilizing jQuery to Toggle Visibility of Table Rows on Button Click

I have a unique layout on my page where there are two tables positioned side by side. The table on the left consists of buttons with company names, and the table on the right should display employees associated with each specific company. Upon initially l ...

Can getServerSideProps be adjusted to avoid triggering a complete page reload after the first load?

My server-rendered next.js app consists of a 3-page checkout flow. The first page involves fetching setup data like label translations and basket items within the getServerSideProps function, as shown below: UserDetails.js import React from 'react&apo ...

Sending data from jQuery to an AngularJS function is a common task that can be accomplished in

In my Controller, I have a function that saves the ID of an SVG path into an array when a specific part of the image.svg is clicked. $(document).ready(function(){ var arrayCuerpo=[]; $('.SaveBody').on("click", function() { ...

Negatives of utilizing two different UI libraries within a single react project?

I have been contemplating a decision that may be considered unconventional from a technical standpoint. Despite my search efforts, I have not come across any explanation regarding the potential drawbacks of this decision. Imagine creating a React website ...

Looking to optimize Laravel performance by eager loading both belongsTo and HasMany relationships?

I have a pair of interconnected models called Product and ProductCategory. Each product belongs to one product category, while each product category can house multiple products. Let's take a look at the models: Product: <?php namespace App\ ...