Child component not reflecting changes in Vue array prop

One issue I encountered is with a model from a backend where the property that typically contains an array of elements can be nullable. To handle this, I initialize it to an empty array. However, this seems to disrupt my ability to update the array in the child component. Here's a snippet of the code:

Vue.component('Notes', {
 template: '<div>{{items}}<ul><li v-for="item in items">{{ item.text }}</li></ul><button @click="add">Add</button></div>',
 props: {
  items: Array,
 },
 methods: {
   add() {
    console.log('added');
    this.items.push({ text: "new item" });
   }
 }
});

new Vue({
 el: "#demo",
 data() { return { model: { }  }},
 created() { if(!this.model.items) this.model.items = []; }
});
<script src="https://unpkg.com/vue"></script>

<div id="demo">
  <Notes :items="model.items" />
</div>

If the data in the main component is model: { items : [] }, everything works as expected. However, I can't guarantee control over the backend data to ensure this.

Answer №1

When working with your Notes component, it is important to properly declare a model in the data section. Creating an items[] directly underneath without checking if it already exists is a risky practice that can lead to issues. Vue requires full knowledge of all properties on objects it watches. These properties should be present when Vue first processes the object, or you can use Vue.set() to add them dynamically. For more information, you can refer to this link.

Answer №2

To update the prop in the parent component, emit an event

Inside the child component :

 this.$emit('add-item',{
        text: "new item"
      });

In the parent template, add a handler for the emitted event :

  <Notes :items="model.items" @add-item="AddItem" />

Vue.component('Notes', {
  template: '<div>{{items}}<ul><li v-for="item in items">{{ item.text }}</li></ul><button @click="add">Add</button></div>',
  props: {
    items: Array,
  },
  methods: {
    add() {
      console.log('added');
      this.$emit('add-item', {
        text: "new item"
      });
    }
  }
});

new Vue({
  el: "#demo",
  data() {
    return {
      model: {
        items: [] //initialize here to avoid reactivity issues
      }
    }
  },
  methods: {
    AddItem(item) {
      this.model.items.push(item)
    }
  },

});
<script src="https://unpkg.com/vue"></script>

<div id="demo">
  <Notes :items="model.items" @add-item="AddItem" />
</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

Ways to display an HTML code by utilizing the onclick() function through PHP?

I have a button that looks like this: <input type="submit" name="submit5" class="btn" value="Add Date" onclick="create_date_field()" /> Every time the button is clicked, I want to append the following code inside the <tr> tags. It should be po ...

Potential memory leak detected in EventEmitter by Discord.js

One night while my bot was running on auto-pilot as I drifted off to sleep, a warning popped up out of the blue: MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 guildMembersChunk listeners added to [Client]. Use emitter.setMaxLi ...

Do you think this is the correct method for developing a component?

Recently, I designed a view to display contact information for the user: <template> <div v-for="user in users" class="user"> <div class="userInformation"> <img :src="user.photo" /> ...

Validate each string in an array using Vuelidate and show corresponding error messages for each item in Vue.js

I have a project in Vue where I gather test answers using forms. I am trying to validate each input with { required } but I am encountering difficulties. The code below checks if there is an array instead of verifying if each string within the array is pre ...

"Error: Trying to access the 'get' property of an undefined object," Axios, Vue.js

I encountered a peculiar error with Vue while attempting to access an API using axios. The error message reads "TypeError: Cannot read property 'get' of undefined" https://i.sstatic.net/eRfSM.png <template> <div class="home&quo ...

What are some effective strategies for avoiding the issue of a hook being invoked multiple times?

Having an issue with my vue3 project. Essentially, I need to handle different layouts for various scenarios such as authorization, user profiles, and group layouts. Here's my approach: Create a component AppLayout.vue to manage layouts <template& ...

I'm struggling to understand the reasoning behind the 'undefined' error occurring in the Google Maps distance service

Currently facing a puzzling issue with an 'undefined' exception. Developing a tool to track distance traveled between two locations, leveraging Google Maps distance matrix. Upon selecting a vehicle, entering an origin and destination, and clickin ...

Positioning a div above a Bootstrap navbar that disappears when scrolling

I am currently using bootstrap to design a website, and I am attempting to create a div that would initially appear above the navbar on an unscrolled webpage. However, once the user starts scrolling, I want this div to disappear and have the navbar fill it ...

What could be the reason my black overlay doesn't show up when the button is clicked?

Attempting to craft a pop-up window on my own, I encountered an issue. Upon pressing the button, instead of the anticipated pop-up appearing and darkening the background below it, the entire page freezes with no sign of the pop-up box. If I eliminate the ...

The operation could not be completed with exit code 1: executing next build on Netlify platform

Having trouble deploying my Next.JS site to Netlify due to a build error. The site was working fine previously. Any suggestions on how to resolve this issue? 3:43:14 PM: - info Generating static pages (2/6) 3:43:14 PM: - info Generating static pages (4/6) ...

Ways to verify the input fields across multiple tabs

Utilizing jquery validate along with jquery tabs to construct a multi-tab form. Consider a basic form : tab 1 for entering address, tab 2 for entering name, tab 3 for submission HTML <ul class="nav nav-tabs"> <li class="active"><a hr ...

What is the best way to have my sliding panel automatically close when I click outside of it?

I have created a sleek sliding navigation panel for my website that appears when the screen width is reduced. Although I am satisfied with how it functions currently, I would like the panel to close when the user clicks/taps outside of it. What adjustments ...

JavaScript random number functionality experiencing an unexpected problem

function generateRandomNumbers(){ var max = document.getElementById('max').value; var min = document.getElementById('min').value; var reps = document.getElementById('reps').value; var i; for (i=0; i<reps ...

The unexpected token was found in line 1 of the manifest icons code, but not in column 1

This query appears to have been long-standing on Stackflow, but none of the solutions posted seem to resolve it. Even though the JSON validates correctly in validators, I continue to encounter the following error. Any idea what might be causing this issue ...

Triggering a Bootstrap 5 dropdown through code is only effective within the browser's developer console, rather than standard JavaScript implementation

I attempted to display a Bootstrap5 dropdown by clicking on a link in my web application. Despite trying various methods, such as dispatching events and utilizing the bootstrap Dropdown classes, I was unable to achieve success. Interestingly, both approach ...

Why does the MEAN Stack continue to route using the '#' symbol in the URL?

Currently navigating the realm of back end development. Started off by following a guide on express from thinkster. In need of some clarification. Initially, I grasped that front-end and back-end routing serve different purposes. Front-end routing relates ...

I attempted to utilize the prop to transfer an object, but unfortunately, the value was not received

I am working with a child component that accepts a todo object. Vue.component('child', { props: ['todo'], template: '<span>{{ todo.text }}</span>' }) var vm = new Vue({ el: '# ...

Execute tests on changing files using cypress.io

I'm currently experimenting with using Cypress to test a large Angular application that I've developed. What I want to achieve is to load an expectation file into my test and then run the test based on this expectation file. Despite trying diffe ...

Utilize jQuery to hide and then show elements based on text input

Recently, I came across a useful jQuery filter example that sparked my interest. To test it out, I created my live example and shared the code on CodePen (or you can check out the Fiddle if you prefer). One issue I encountered was that after entering text ...

Vue: A guide to fetching and displaying response data in a select dropdown using the vue-search-select component and axios

Hi there, I am new to this platform. I am facing an issue while trying to display response data from axios on the select option using vue-search-select. Despite several attempts, I have been unsuccessful in getting the desired results. I managed to loop th ...