Vue.js: Issue with updating list in parent component when using child component

I'm encountering an issue when utilizing a child component, the list fails to update based on a prop that is passed into it.

When there are changes in the comments array data, the list does not reflect those updates if it uses the child component <comment></comment>.

Template for TopHeader:

<template>
    <ul v-for="comment in comments">

        // When not using a child component, it updates every time the `comments` array is modified:

        <li>
            <div>
                /r/{{comment.data.subreddit}} ·
                {{comment.data.score}}
            </div>
            <div class="comment" v-html="comment.data.body"></div>
            <hr>
        </li>

    </ul>
</template>

TopHeader component details:

import Comment from 'components/Comment'

export default {
  name: 'top-header',
  components: {
      Comment
  },
  data () {
    return {
      username: '',
      comments: []
    }
  },
  methods: {
      fetchData: function(username){
          var vm = this;
          this.$http.get(`https://www.reddit.com/user/${username}/comments.json?jsonp=`)
          .then(function(response){
              vm.$set(vm, 'comments', response.body.data.children);
          });
      }
  }
}

However, the problem arises when I introduce a child component.

Updated TopHeader template:

<template>
    <ul v-for="comment in comments">

        // Instead of directly rendering, I use a component with prop data, but it doesn't get updated
        <comment :data="comment.data"></comment>

    </ul>
</template>

Template for Comment child component:

<template>
    <li>
        <div>
            /r{{subreddit}} ·
            {{score}}
        </div>
        <div class="comment" v-html="body"></div>
        <hr>
    </li>
</template>

Details of Comment child component:

export default {
  name: 'comment',
  props: ['data'],
  data() {
    return {
        body: this.data.body,
        subreddit: this.data.subreddit,
        score: this.data.score,
    }
  }
}

Answer №1

Try moving the v-for statement to the <comment> component instead of having it on the ul-tag. Placing the v-for on the ul-tag will cause the ul tag to repeat. Take a look at this example for more guidance.

<div id="app">
    <button v-on:click="fetch">Fetch data</button>
    <ul>
        <comment v-for="comment in comments" v-bind:comment="comment" />
    </ul>
</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

The presence of onChange?: (ValueType, ActionMeta) => void with OptionType is not compatible

After updating to version v2.4.2, I keep encountering an error from flow regarding react-select. It seems that I am passing the correct types to the handle change, which expects an array with objects + OptionType accepting any string [string]: any. Can som ...

Struggling to align elements in React/JS/M?

My challenge is aligning the elements in the middle of my page. I aim to have 3 elements per row, with n rows depending on the number of "VideoBox" components. It's crucial that these elements fit within the lettering of the P R O F E S S I O N A L ...

Accessing a factory's functions within itself in Angular

I'm really trying to understand how all of this operates. It seems like it should be working as intended. I have an Auth factory that, when the jwt token expires, calls its 'delegate' method which obtains a new token using the refresh token. ...

Issue with Apollo Client - Mutation failing due to undefined property 'data'

When attempting to call a mutation on the client side in Next.js, I encounter an error every time I use the useMutation hook or the client itself, resulting in the following error: Cannot read property 'data' of undefined. See the code snippets b ...

Break down React website into distinct modules and bundle them as npm dependencies within a single package

Currently, I am developing a React website that includes distinct sections such as contact management and message management. Each of these sections is quite extensive. To navigate to these sections, we use a single dashboard for control. Since separate ...

Track and monitor data modifications in Vue.js

I recently incorporated a Bootstrap Vue Table into my application and wanted to monitor user activity as they navigate through the pages using the pagination feature. Here is where you can find more information on the Bootstrap Vue Table To achieve this, ...

How can I render just one event instead of all events when using the eventRender callback function?

I am currently working on adding an event to my calendar using a JSON format with specific attributes like id and start time. Here is what I have tried so far: $('#calendar').fullCalendar('renderEvent', my_event); $('#calendar& ...

Buffering ceases on the video

I am experiencing an issue with 4 videos and a preloader, which should hide once all the videos are fully buffered. <div id="preload"> <h1> Download... </h1> </div> <video preload="auto" class= ...

Dealing with Oversized Images in Jcrop: Tips and Tricks

Utilizing Jcrop for cropping images, everything runs smoothly with small images. However, when I attempt to use large images like 2080x2080 or 1600x1600, it takes up the entire screen and cannot be controlled by CSS properties such as width and height in t ...

The requested resource lacks the 'Access-Control-Allow-Origin' header in a basic HTML form

Can someone help me understand why I keep encountering this error in my basic HTML form? I am attempting to display XML data on my website to showcase news stories, but unfortunately, I keep getting stuck with this persistent error. Any assistance would ...

Tips on how to bring in a module from index.js

Recently, I set up a sample node.js project: "name": "example", "version": "1.0.0", "type": "module", Let's take a look at the index.js (only two lines): "use strict"; import ...

Notification for background processing of $http requests

I am searching for a solution to encapsulate all my AJAX requests using $http with the capability to display a loading gif image during processing. I want this functionality to extend beyond just $http requests, to cover other background processing tasks a ...

What is the reason for Jest attempting to resolve all components in my index.ts file?

Having a bit of trouble while using Jest (with Enzyme) to test my Typescript-React project due to an issue with an alias module. The module is being found correctly, but I believe the problem may lie in the structure of one of my files. In my jest.config ...

Is there a way to remove the "next" button from the last page in a table?

I'm currently working on implementing pagination for my table. So far, I have successfully added both the "next" and "previous" buttons, with the "previous" button only appearing after the first page - which is correct. However, I am facing an issue w ...

splitting xmlhttp.responsetext using loops

Currently, I have a JavaScript function that utilizes xmlhttp.responsetext to fetch data from MySQL. This data is then used to populate form fields in a dropdown menu, which has been functioning perfectly so far. However, the issue arises when I attempt to ...

"The use of Node.js and Express.js in handling HTTP requests and responses

I am intrigued and eager to dive deep into the request and response cycle of backend development. Here's my query: I have a node.js express framework up and running. The app is launched and all functions are primed and ready for requests. app.use(&a ...

What is the best way to delete an added element once a DIV has been toggled with JQuery?

I'm facing an issue where I need to add an element to a DIV that has a toggle function. However, every time I click the toggle again after adding the element, the same element is appended once more, resulting in duplicate elements. Upon observation, ...

Encountering an issue in Laravel when trying to retrieve data using relationships and the paginate() method

When I try to fetch data using paginate(10), Vue.js does not work. However, if I use paginate(5), it works fine. The code in the Controller with relationships in the model files is working fine and returns a 200 OK response. $results = Posts::with([' ...

What is the best way to incorporate Express following an asynchronous function?

After setting up my Firebase and initializing it, I managed to retrieve data from it. However, I encountered an issue when trying to use express.get() and json the data into the server. I'm unsure of what the problem could be. let initializeApp = requ ...

Employ ImageMagic in a synchronous manner

Consider utilizing imagemagick Required to use imagemagick in a synchronous manner. Meaning the following code should execute only after the image conversion is complete (regardless of any errors). The only solution I can see involves using deasync: co ...