Using the v-model directive in Vue.js with a for loop is

I am facing a challenge where I need to implement a v-for loop with multiple components, but I am unsure how to add a unique v-model to each component that is generated within the loop.

<template>
<ProfilePasswordField
      v-for="(item, index) in profilePasswordItems" 
      :key="index"
      :profilePasswordItem="item"
      v-model="???"
>
</template>

The v-for loop will always have three items, and I would like to assign the v-model names as: ['password', 'newPassword', 'confirmNewPassword']

Is there a way to dynamically set these v-model names within the v-for loop?

I attempted to create a list inside the data() function, but it was unsuccessful. My attempt looked like this:

data (){
        return{
            listPassword: ['password', 'newPassword', 'confirmNewPassword']
        }
},
methods: {
        method1 () {
            console.log(this.password)
            console.log(this.newPassword)
            console.log(this.confirmNewPassword)
       }
}

Answer №1

When using the v-model directives, it's important to note that they cannot directly update the iteration variable itself. Therefore, it's recommended not to use a linear array item in a for-loop as the v-model variable.

One alternative method you can try is as follows-

In the parent component-

<template>
  <div>
    <ProfilePasswordField
      v-for="(item, index) in listPassword" 
      :key="index"
      :profilePasswordItem="item"
      v-model="item.model"
    />
    <button @click="method1()">Click to see changes</button>
 </div>
</template>
    
<script>
  export default {
  name: "SomeParentComponent",

  data() {
    return {
      listPassword: [
        { model: "passaword" },
        { model: "newPassword" },
        { model: "confirmNewPassword" },
      ],
     };
   },
    
   methods: {
     method1() {
       this.listPassword.forEach((item) => {
         console.log(item.model);
       });
     },
   },
  }
 </script>

In the ProfilePasswordField component, you can emit the input event to track changes in the v-model binding. For example, the ProfilePasswordField component could be like this-

<template>
  <v-text-field :value="value" @input="$emit('input', $event)"/>
</template>

<script>
 export default {
   name: "ProfilePasswordField",

   props: {
    value: {
     required: true 
    } 
 }
</script>

By checking the parent component's console, you should be able to observe the changes made by the child component.

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

Retrieve values from the query string (specifically from table rows and cells) for each individual line and display them in

i have some code, see: <script> $$.ready(function() { // Profile Dialog $( "#user-dialog" ).dialog({ autoOpen: false, modal: true, width: 400, open: function(){ $(this).parent().css('overflow', 'visible') ...

Toggle button with v-bind in Nativescript Vue

Hey there, I'm just starting out with nativescript vue and I have a question regarding a simple "toggle" feature that I'm trying to implement. Essentially, when a button is pressed, I want the background color to change. <template> < ...

Utilizing the $scope variable within an event in the Google Maps API

I am having an issue using $scope within this function. Where should I define the argument $scope so that it works properly? Thank you Below is the basic structure of my code with key lines included: myApp.controller('myCtrl', ['$scope&ap ...

Guide on how to streamline JSON output from aggregation result

I have written a NodeJs api using mongo db aggregation to obtain some output. However, the result I received is not what I expected. Can anyone help me figure out how to get the desired output? app.get('/polute', function (req, res) { Light. ...

Utilizing JavaScript for enhancing the appearance of code within a pre element

Is there a way to dynamically highlight the code inside a pre element using vanilla JavaScript instead of JQuery? I'm looking for a solution that colors each tag-open and tag-close differently, displays tag values in another color, and attributes with ...

Display the outcome of a POST request on the webpage

Currently working with node.js/express and have a view that includes a form. This form POSTs to a route which returns JSON data. I want to be able to submit the form and display the returned data underneath the form on the same view without refreshing the ...

What are the best scenarios for implementing jQuery-ui plugin as opposed to Backbone View?

I am feeling uncertain about the concept of "componentization" in web UI development. When I need a component, should I develop my own jQuery-UI plugin or opt for creating a MarionetteComponent if I am using Backbone.Marionette? Both options provide reusa ...

Error: The property 'setDirections' of undefined cannot be read in Google Maps

As a novice in using the Google Maps API, I am seeking assistance regarding an error I encountered: An issue arises with my code displaying: Uncaught TypeError: Cannot read property 'setDirections' of undefined This occurs at line 101 in google- ...

No visible changes from the CSS code

As I create a small HTML game for school, I'm facing an issue with styling using CSS. Despite my efforts to code while using a screen reader due to being blind, the styling of an element isn't being read out as expected. The content seems to be c ...

React's `setState` function seems to be failing to update my rendered catalog

Managing a shopping catalog where checkboxes determine the rendered products. The list of filters serves as both the menu options and state variables. The actual products in the products list are displayed based on the selected categories. const filters ...

Tips for saving a JavaScript function in JSON format

Looking to store a JS object in Local Storage for future reference, but struggling to convert it to a string. Here’s the code: JSON.stringify({ x: 10, y: function (input) { return input; } }) As a result, I get: "{"x":10}" Any su ...

The page you are looking for cannot be located using Jquery AJAX JSON PHP POST -

Whenever I attempt to POST some JSON data to a local host, I consistently encounter a 404 Not Found error. Strangely enough, the php file is positioned precisely where it should be according to the script instructions. If anyone has dealt with this issue b ...

How to Handle Tab Navigation on a Mobile Website without Javascript?

My website primarily targets mobile devices, with tabs in the top navigation. Currently, these tabs are hard coded instead of utilizing Javascript. We want to ensure our site is accessible on all mobile devices, including those without Javascript support. ...

How to arrange three buttons in a row using CSS styling

After reviewing similar issues posted by others, I have not found a solution to my problem. Despite trying the suggested solutions, I am unable to center two buttons representing different departments on my webpage. Here is my source code: <script ...

Having trouble with Vue JS code to determine if a user is logged in

I am working on a Vue.js project and I am trying to implement a feature where the user needs to be logged in to access the website. If they are not logged in, they should be redirected to the /login page. As a beginner in Vue.js, I attempted the code below ...

Having trouble displaying HTML UL content conditionally in Reactjs?

My goal is to display a list of items, limited to a maximum of 5 items, with a "more" button that appears conditionally based on the number of items in the list. However, I am encountering an issue where passing in 5 li items causes them to be rendered as ...

Dealing with shared content in your Capacitor Android application may require some specific steps

As a beginner in android development, I am currently embarking on my first Capacitor Android app project using Quasar/Vue. My goal is to enable the app to receive files/images shared from other apps. Through research, I have discovered how to register my a ...

Tips for enabling resize functionality on individual components one at a time

Check out my Codepen link for the resizable event While using Jquery UI resizable, everything is functioning correctly. However, I am now looking to have the resizable event activate one block at a time. When another block is clicked, the resizable event ...

Troubleshooting: Why is my console.log not working in JavaScript

Recently, I've been diving into the world of JavaScript, but for some reason, I can't seem to make console.log function properly. At the top of my HTML document in the head section, I added jQuery like this: <script type="text/javascript" sr ...

What steps should I take to resolve the "StrictMode has found deprecated findDOMNode" error?

Whenever I trigger the button to open the drawer, my console displays the warning message '' findDOMNode is deprecated in StrictMode'' The container for the button component is called Sidenav import Sidenav from './Sidenav'; ...