Vue encounters an issue when trying to access a specific field within an array of objects

Consider the following data structure:

    rules:[
    0:{
      subrule1:'',
      subrule2:'',
      subrule3:''
    },
    
    1:{
      subrule1:'',
      subrule2:'',
      subrule3:''
    }   
   ]

and it can be iterated through like this:

<div v-for="(fields, index) in rules" :key="index">

    <div>
      <button @click.prevent="addMore()">
        Add Rules
      </button>
    </div>

    <div>
       <button @click.prevent="deleteSubrule(index)">
          Delete
       </button>    
    </div>

      <input
        name="subrule1"             
        :value="getAdditionalIndex(index, 'subrule1')"
       />

      <input
        name="subrule2"             
        :value="getAdditionalIndex(index, 'subrule2')"
       />

      <input
        name="subrule3"             
        :value="getAdditionalIndex(index, 'subrule3')"
       />

</div>

The corresponding methods are:

   getAdditionalIndex(index, field) {
      return this.rules[index][field];
   },

  addMore(){
    const fields = {
        subrule1:'',
        subrule2:'',
        subrule3:''
      };

    this.rules.push(fields)
  },

  deleteSubrule(index){
    this.$delete(this.rules, index)
  }

However, there might be issues with data binding and deletion errors. Deep watchers are usually used with child components but not directly on v-for elements. Is there a solution that allows deep watchers in this context?

Below is a runnable snippet for reference:

  
<html>
<div id="app">

    <div>
      <button @click.prevent="addMore()">
        Add Rules
      </button>
    </div>

    <div>
     <button @click.prevent="showStates()">
        Show state results
      </button>
    </div>
  <div v-for="(fields, index) in rules" :key="index">
    <div>
       <button @click.prevent="deleteSubrule(index)">
          Delete
       </button>    
    </div>

      <input
        name="subrule1"             
        :value="getAdditionalIndex(index, 'subrule1')"
        @input="inputChange"
       />

      <input
        name="subrule2"             
        :value="getAdditionalIndex(index, 'subrule2')"
        @input="inputChange"
       />

      <input
        name="subrule3"             
        :value="getAdditionalIndex(index, 'subrule3')"
        @input="inputChange"
       />

      </div>
</div>

<!-- Don't forget to include Vue from CDN! -->
<script src="https://unpkg.com/vue@2"></script>
<script>
  new Vue({
    el: '#app', //Tells Vue to render in HTML element with id "app"
    data() {
      return {
         rules:[],
         test:''
      }
    
    },
    
    methods:{ 
       addMore(){
          const fields = {
            subrule1:'',
            subrule2:'',
            subrule3:''
          };
        this.rules.push(fields)
      },
      
       deleteSubrule(index){
       this.$delete(this.rules, index)
       },
       
       
      getAdditionalIndex(index, field) {
      return this.rules[index][field];
      },
      
      inputChange(event){
        return event.target.value
      },
      
      
      showStates(){
        alert(JSON.stringify(this.rules))
      }
      
      
      
       
       
      
      
      
    }
  });
</script>
</html>

Answer №1

Instead of utilizing the term additional, it is recommended to pass the index to the getAdditionalIndex method

<html>
<div id="app">

    <div>
      <button @click.prevent="addMore()">
        Add Rules
      </button>
    </div>
  <div v-for="(fields, index) in rules" :key="index">
    <div>
       <button @click.prevent="deleteSubrule(index)">
          Delete
       </button>    
    </div>

      <input
        name="subrule1"             
        :value="getAdditionalIndex(index, 'subrule1')"
       />

      <input
        name="subrule2"             
        :value="getAdditionalIndex(index, 'subrule2')"
       />

      <input
        name="subrule3"             
        :value="getAdditionalIndex(index, 'subrule3')"
       />

</div>
</div>

<!-- Don't forget to include Vue from CDN! -->
<script src="https://unpkg.com/vue@2"></script>
<script>
  new Vue({
    el: '#app', //Directive for rendering in HTML element with id "app"
    data() {
      return {
         rules:[]
      }
    
    },
    
    methods:{ 
       addMore(){
          const fields = {
            subrule1:'',
            subrule2:'',
            subrule3:''
          };
        this.rules.push(fields)
      },
      
       deleteSubrule(index){
       this.$delete(this.rules, index)
       },
       
       
      getAdditionalIndex(index, field) {
      return this.rules[index][field];
      },
       
       
      
      
      
    }
  });
</script>
</html>

It is advisable to use v-model in the input fields to prevent clearing as you add new rows, eliminating the need for the getAdditionalIndex function

<html>
<div id="app">

    <div>
      <button @click.prevent="addMore">
        Add Rules
      </button>
    </div>
  <div v-for="(fields, index) in rules" :key="index">
    <div>
       <button @click.prevent="deleteSubrule(index)">
          Delete
       </button>    
    </div>

      <input
        name="subrule1"             
        v-model="fields.subrule1"
       />

      <input
        name="subrule2"             
        v-model="fields.subrule2"
       />

      <input
        name="subrule3"             
        v-model="fields.subrule3"
       />

</div>
</div>

<!-- Don't forget to include Vue from CDN! -->
<script src="https://unpkg.com/vue@2"></script>
<script>
  new Vue({
    el: '#app', //Directive for rendering in HTML element with id "app"
    data() {
      return {
         rules:[]
      }
    
    },
    
    methods:{ 
       addMore(){
          const fields = {
            subrule1:'',
            subrule2:'',
            subrule3:''
          };
        this.rules.push(fields)
      },
      
       deleteSubrule(index){
       this.$delete(this.rules, index)
       },     
    }
  });
</script>
</html>

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

Tips for retrieving the checked status of a Material UI <Checkbox/> component and changing it to false upon clicking a different icon (such as a delete icon)

Greetings! I have encountered a problem that I am hoping someone can assist me with. I am looking for information or guidance on how to handle a specific issue. The challenge I am facing involves accessing the checked property of a material-ui <Checkbo ...

Vue CLI-generated project experiencing issues with embedding Font Awesome code

After setting up a Vue project using the Vue CLI, I received an embed code for Font Awesome 5 in my email. I proceeded to insert this code into the index.html file located in the public folder of my project. <head> <script src="https://use.font ...

What is the best way to determine whether a YouTube video permits embedded playback?

When working with user-generated content, it's important to note that YouTube channels may restrict their videos from being played in an embedded player. In order to provide a better user experience, I need to detect the specific reason why a video ca ...

Hide the menu when tapping outside on a tablet device

Currently working with HTML, CSS, and JS (specifically Angular) I have a Header menu that contains dropdown sub-menus and sub-sub-menus in desktop view. On a PC, the sub-menus appear on hover and clicking on an entry redirects you somewhere. Clicking o ...

Tips for preventing redundant AJAX calls following a setTimeout

I have a text field where I check the database for matches when users type. However, I want to avoid overloading the database with unnecessary queries if someone quickly types several characters. After browsing the internet, it seems like the recommended ...

Exploring Facebook Graph Data with Meteor 1.3

During my time using Meteor 1.2, I utilized the following code on my server to access user data and friends data: function Facebook(accessToken) { this.fb = Meteor.npmRequire('fbgraph'); this.accessToken = accessToken; this.fb.setAcc ...

Having trouble getting Tailwindcss to work with Next.js - what could be causing the configuration issue?

Why is tailwind not displaying correctly in my next.js project? I'm concerned that there might be a problem with my settings. In the styles folder, I have a file called tailwind.css @tailwind base; /* Write your own custom base styles here */ /* S ...

Optimize data storage with javascript on Otree

I've been attempting to store the timestamp from a click in an Otree database, but I've tried using various codes without success. Here's the first code snippet: function myFunction() { var n = Date.now(); document.getElementById(" ...

The type 'Observable<Response>' does not include a property called 'map'

I recently started learning angular and npm, but encountered an error while trying to replicate some code from a source I found (linked here). It seems like the error is related to my development environment, but I'm having trouble pinpointing the ex ...

Module logo.svg not found? Error in Typescript

Integrating package: vue-svg-loader. Established the file svg.d.ts with the content below: declare module '*.svg' { const content: any export default content } Utilizing it in a component in the following manner: import register from &apo ...

Linking a pair of checkboxes

I am dealing with two checkboxes on my website. <input class="checkbox1" type="checkbox" name='1' id="example1" value="example1"/> and <input class="checkbox2" type="checkbox" name='2' id="example2" value="example2"/> I ...

Encountering issues while creating a basic digital clock webpage using React

I am trying to create a simple clock in React, but I want all the time data to be stored in a single object instead of separate states for hours, minutes, and seconds. However, I keep running into an error. Can someone please assist me? import React from & ...

Press the jQuery button to reset all input fields

I have created a table with input fields where class teachers can store their students' data for the principal to review. Each row in the table contains an update and reset button, allowing teachers to save or clear the information entered in the fiel ...

Adjusting the slider with jQuery and CSS to extend beyond 100% while remaining within the div boundaries

Currently, I'm working on customizing a jQuery slider. My goal is to achieve the same functionality as the jQuery UI slider where you can set a max value like "2500" and the slider will smoothly adjust without going outside of the specified div or scr ...

Which costs more, using an undefined ng-bind or both ng-bind and ng-show together?

Assuming that toShowVar is undefined, which of these options would be more costly? <span ng-bind="toShowVar" ng-show="toShowVar"></span> or <span ng-bind="toShowVar"></span> The latter option would clearly not display anything o ...

Creating personalized categories with Material-UI's Autocomplete feature in a React application

I've been attempting to customize the groupings in the MUI Autocomplete component, but I haven't had any luck so far. It seems like there is no built-in solution provided by the library (I hope I'm mistaken). The first grouping can be achie ...

Creating a dynamic sidebar menu with clickable submenus through jQuery and CSS for a user-friendly experience

<div id="sidebar" class="sidebar"> <div class="slimScrollDiv" style="position: relative; overflow: hidden; width: auto; height: 100%;"> <div data-scrollbar="true" data-height="100%" data-init="true" style="overflow: hidden; width: a ...

When the user clicks on a specific element, ensure that it is the main focus and generate an overlay

One of my challenges is implementing a custom element that captures user input upon clicking, focusing on it and overlaying other elements. I want the overlay to disappear if the user clicks outside the div. I attempted to achieve this using the iron-over ...

Determine the number of input tags within a div element by utilizing the closest property in jQuery

Sorry for the silly question, but I've been struggling to find a solution. Spent hours scratching my head. Here is my HTML structure: <div class= 'container'> <div class="someclass"> <input>some content</in ...

Incorporating a YouTube or Vimeo video while maintaining the proper aspect ratio

On my video page, I embed Vimeo videos dynamically with only the video ID. This causes issues with the aspect ratio as black bars appear on the sides due to the lack of width and height settings. The dynamic video ID is implemented like this: <iframe ...