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

Execute the dynamic key API function

Below is the data object: registration: { step1: { project: '', }, step2: { adres: '', facade: '', floor: '', }, }, An attempt is being ...

Issue with Yeoman webapp generator and Gulp, encountering error when using Gulp-jade package

I'm encountering some difficulties integrating jade with yeoman's gulp webapp generator. The watch task is functioning properly, but when I attempt to build the project, I encounter the following error: stream.js:94 throw er; // Unhandled ...

Changing images dynamically in tinymce using JavaScript

When using the tinymce editor, I attempt to modify my images. I currently have an image within it and I am trying to dynamically change the path of this image with: tinymce.activeEditor.selection.getNode().src = '/my/path/' Surprisingly, this m ...

Determine whether an element is currently focused using a Vue.js directive

I'm attempting to verify if an element is currently in focus, specifically an input field, and then apply a class to another element. This is the code I have been working on, but for some reason the hasFocus() function isn't functioning as expect ...

What is the best way to ensure an AJAX get-request waits for the page to finish rendering before providing a response?

I've been working on a Greasemonkey Script for a specific section of this website (Site1). Site1 offers various deals and discounts, and my script is designed to perform the following task: When a user visits an offer on Site1, the script checks with ...

Animated smooth updates in d3 line graphs are the key to creating dynamic and

I'm attempting to modify an example of Animated Line Graphs from: http://bl.ocks.org/benjchristensen/1148374 <div id="graph1" class="aGraph" style="width:600px; height:60px;"></div> <script> function draw(id, width, height, upd ...

Organize every rectangle and text element in D3 into distinct groups

Currently, I am working on creating a bar graph using d3.js. The goal is to display text on top of each bar when the user hovers over it. To achieve this, the <text> and <rect> elements need to be grouped inside a <g> element. For Exampl ...

What are the best practices for managing promises effectively?

Currently, in my Angular application, I am utilizing $odataresource for handling data retrieval and updates. The code snippet I am working with is as follows: var measure = $odataresource("http://windows-10:8888/ChangeMeasure/"); var myMeasure = measure ...

Leveraging the Nest JS Validation Pipe in combination with the class-transformer to retrieve kebab-case query parameters

Can someone help me with using the Nest JS Validation Pipe to automatically transform and validate my GET Request Query Params? For example: {{url}}/path?param-one=value&param-two=value In my app.module.ts, I have included the following code to impl ...

Leveraging PHP for populating JavaScript variables

I am currently working on populating a Drop-Down menu from a csv file stored on a network share. So far, I have successfully managed to populate the options when the file is in the wwwroot folder. However, I am now encountering an issue with referencing a ...

When creating a FlipCard, you may encounter the error message "The object may be null" while using the document.querySelector() method

Having trouble creating a flipcard on Next.js with tsx. The querySelector('.cardflipper') doesn't seem to locate the object and I keep getting this error: "Possibly the object is null". Does anyone know a solution to help my method recognize ...

What is the best way to display an image and text side by side within a single row in react-table?

I am trying to display an image and text side by side within a single column in a React table. I have successfully added two texts together in a single column using the code below: Header: "Name", id: "User", accessor: (d) => ...

When the Protractor configuration is executed, it displays the message "The requested webpage cannot be accessed."

Testing protractor on a vanilla.js app and encountering an error when running protractor basicConf.js The following error is occurring: This webpage is not available ERR_CONNECTION_REFUSED Here is the test script in use: describe('foo', fun ...

Interactive questioning system using Javascript/jQuery for Quick Responses

Hi there! I'm new to StackOverflow and a bit of a beginner when it comes to javascript/jquery. My current project involves creating a chat interface that looks like SMS text messages. Right now, I have users inputting text and using javascript to disp ...

use dotenv in your Build Folder

Is it possible to have my .env file in my React JS project move to the build folder when I run NPM build command? If so, how can this be achieved? If not, what would be the alternative solution? I attempted using "build": "cp .env.template ...

Having trouble finding the sum of values in an array using the Reduce method?

I have always used a 'for' loop to calculate sums in tables, but recently I learned about a better way - using the 'reduce' method. Following documentation and examples with simple arrays was easy enough, but now I am working with an ar ...

When initially compiling Angular 5, an error (TS2339) may occur, but after a successful compilation, everything runs smoothly

In a unique scenario, I wrote code that fetches information from an API server without knowing the structure of the response fields. Once I receive the response, I need to create a form for updating the data and sending it back. To handle unknown ngModel p ...

"Exclusive Mui sx styles will be applied only when a specific breakpoint

As I update my old mui styling to utilize the sx attribute, I've noticed the ability to specify styles for different breakpoints using sx = {{ someCssProp: { xs: ..., md: ... and so on. Prior to this, I had been using theme.breakpoints.only for some ...

Is it possible to retrieve data from the server in Node.js/Vuetify based on a specific time frame?

I'm currently using a node.js server for my vuetify project. Within the server, I am parsing a csv file that contains scheduling and time information. Is there a method in my vuetify project to retrieve data from the csv file based on the current time ...