Implementing watch functionality with array in Vuejs for bidirectional communication between parent and child components

Here is a simplified version of a parent component I created:

// parent component

<template>
   <layout
    v-for="(value, idx) in array"
    :pickUpLength="array.length"
    :idx="idx"
    :key="idx"
   >
   <button @click="addArray">add</add>
</template>

data(){
  array:[
     {"date" : "", "time": ""},
     {"date" : "", "time": ""}
  ]
}
methods:{
  addArray(){
     this.array.splice(this.array.length - 1, 0, {"yes":"no"})
  }

I also have a child component.

<template>

</template>

props:["pickUpLength"],
watch:{
    pickUpLength:{
      handler(){
          console.log(idx)
      }
   }
}

When the addArray button is clicked in the parent component, the pickUpLength of the child component gets updated as well. However, the problem arises when the console.log(idx) only displays "0, 1" instead of "0, 1, 2", even though there are three items in the array. I'm seeking advice on how to resolve this issue. Thank you for your help and for taking the time to read through it.

Answer №1

<template>
   <layout
    v-for="(value, idx) in array"
    :pickUpLength="array.length"
    :idx="idx"
    :key="idx"
   >
   <button @click="addArray">add</add>
</template>

<script>
export default {
  data() {
    array:[
      {"date" : "", "time": ""},
      {"date" : "", "time": ""}
    ]
  },
  methods:{
    addArray(newVal){
      // In Vue.js v2.x.x you can't "watch" arrays or Objects. This is a workaround for adding elements to an array.
      
      this.array = this.array.slice(0, this.array.length - 1).concat(newVal, this.array[this.array.length - 1]);
    }
  }
};
</script>

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

Why isn't my script responding to mouse events like mouseenter, mouseover, or any other mouse event?

const element = document.getElementById("box"); element.addEventListener("mouseenter", handleMouse); function handleMouse(event) { console.log("Event type: " + event.type); } ...

What steps can I take to trigger a 404 error instead of a cast error?

My route is defined as /mysafe/idofthemodel. When the idofthemodel is not found, it throws a cast error Cast to ObjectId failed for value "something" (type string) at path "_id" for model "modelname". Instead of this error, I ...

What is the method for including a class in the anchor element that is the closest sibling of the containing ul element in the HTML structure?

I'm currently exploring traversal in jQuery and I'm a bit confused about how the class is being added to all the items in the unordered list. I know it's probably something simple that I'm missing. Any assistance would be greatly apprec ...

Troubleshooting lpush errors in Node.js with Redis

I'm currently developing a web application using node.js and redis. The goal is to store each incoming request in a redis queue before saving it into a database. However, I keep encountering an error whenever the program executes the lpush command. Be ...

Creating multiple nested ng-repeats in an AngularJS table

Managing a large amount of data on users' availability by hour for multiple days can be challenging. The data is structured as follows: availData = { "date1":arrayOfUsers, "date2":arrayOfUsers, ... } arrayOfUsers= [ userArray, userArray, ... ] user ...

Node.JS, R, and Python are used for intensive computing tasks such as identifying when a callback function has finished executing and

My Node.js REST API exposes endpoints that trigger R and Python scripts for complex computations. Prior to executing these scripts, I must first identify the callback, assign a unique ID to it, and quickly send back the ID to the consumer. The consumer wil ...

Tips for managing $rootScope in the provider's config function

Can someone help me understand how to work with $rootScope in a provider method? I'm unsure of how to properly inject it. that.app.config ['$authProvider', ($authProvider) -> $authProvider.configure apiUrl: '/api/v1&apos ...

Press `Enter` to confirm your selection in the BootstrapVue message box input box

Using Vue version v2.6.12 BootstrapVue version v2.21.2 Is there a way to confirm by pressing Enter instead of manually clicking OK? let text this.$bvModal.msgBoxConfirm(<input vModel={text} />) https://i.sstatic.net/7XxOl.png ...

Utilizing Bootstrap combobox to easily select values by typing them in

I recently started utilizing the bootstrap combobox plugin on my website. Strangely, I've noticed that when selecting from the options in the dropdown list, choosing NewYork works smoothly. However, if I type "New" and attempt to select "New York" fr ...

Display a message box in the external window just before the close event

I am trying to implement a message box that will appear when the user clicks the (X) button of an Ext window. However, I am facing an issue where the window closes before the message box is shown. Below is the code snippet I have written: var assignReport ...

Best practice for passing a variable argument in a JavaScript callback?

After searching the internet without success, I couldn't find the answer to my problem. The issue revolves around a function that I have: function ParentFunction (DataBase, Parameters) { for (k = 0; k < DataBase.length; k++){ var ...

Issue with ng-bind-html in TranslateJS causing problems

I have been working on implementing translation in a web application using angularJS and the angular-translate repository, which can be found at . As per the documentation, it is possible to use this repository to set text for a specific element in the HTM ...

Advantages of choosing between the <NextLink/> and the <Button href="/somePage"/> components in the powerful Mui React UI libraries

Currently engaged in a project, I am wondering if there exists a substantial disparity in the utilization of these two components. Prior to this change, the return button was implemented as follows: <NextLink href="/settings" ...

Implementing setState in React with nested objects and dynamic keys

Here is how my state appears: state = { basic: { entry: 'index.js', output: { path: 'dist', filename: 'bundle.js', } } } An onChange event callback for input has been defined as follows: handleU ...

The width of the table remains consistent

I have created a division that includes two tables stacked on top of each other. However, I am facing an issue where the width of the second table remains fixed and does not change even when I try to increase it. Here is the code snippet below: functio ...

JavaScript compilation failure: Unhandled SyntaxError: Unforeseen token '>' in string variable within an if statement -- Snowflake

Looks like there's an issue with JavaScript compilation. The error message reads: Uncaught SyntaxError: Unexpected token '>' in HP_SEARCHCBHMESSAGES at ' if (Fac123 <> "") ' position 1.. Strange how SF is not a ...

Ext JS - A grid cell containing varying values, accompanied by a selection of combo boxes

I'm currently implementing the Ext JS Grid component and have a list of fields with their respective data types: ID (int) Name (string) Foods (List<string>) Each user can have multiple foods, selected from a Food DataStore. Displaying this in ...

When using Vue.js and Laravel, the DOM does not accurately display the updated array data after an axios call

After countless attempts to solve this issue on my own, I have decided to seek help here. I am relatively new to programming and currently working with laravel + vue.js + mysql. My Approach My process involves fetching data through an Axios call and upd ...

The issue of resolving NestJs ParseEnumPipe

I'm currently using the NestJs framework (which I absolutely adore) and I need to validate incoming data against an Enum in Typscript. Here's what I have: enum ProductAction { PURCHASE = 'PURCHASE', } @Patch('products/:uuid&apos ...

Disable or eliminate the event listener

Working on my Angular2 application, I've set up an RxJS timer that sends notifications to users when they are logged in. The twist is, the notification should only be sent if the tab is active; otherwise, the scheduler should pause or stop. I have man ...