Vue.js is not properly synchronizing props in a child component when the parent component is updating the property

When it comes to communication between components, my structure looks something like this:

<div id=chat-box>
<div class="wrapper">
  <div>
    <chat-header></chat-header>
    <message-container :chat="chat"></message-container>
    <chat-compose @clicked="onClickChild"></chat-compose>
  </div>
</div>

The parent component:

methods: {
onClickChild (value) {
  console.log('in top parent');
  this.chat = value;
},

The first child component:

methods: {
  startChat: function(event) {
    this.$emit('clicked', new chat({
     type: 'user',
     message: this.input_value,
     button: 'user',
     metaInfo: 'user',
     isBot: false,
   }))
  },
},

The second child component:

export default { name: 'messageContainer', props: ['chat'],

data: function() {
  return {
    chatSession: [],
  }
},

method : {
  updateData : function() {
    console.log('called updatedata');

  }
},

created: function () {
  console.log(this.chat) 
},
mounted: function () {
 console.log(this.chat) 
},

updated: function() {
  console.log(this.chat)
}

}

After clicking on the child method and emitting it to the parent for an update, the message-container component does not reflect the updated value. Despite attempting to use created, mounted, and updated methods to achieve this, they only execute once during app initialization and do not trigger again upon data changes.

In summary, there are three components in total – one parent and two children. The issue arises when one child updates the chat object, emits it to the parent, and the parent passes the same updated child to another child which fails to re-render or receive the updated value. Any guidance on a better approach would be greatly appreciated.

Answer №1

It appears that Vue may be utilizing caching for the <message-container> component.

To resolve this issue, consider including a :key within the component to trigger a re-render.

 <message-container :chat="chat" :key="count"></message-container>

You can also implement a counter in your onClickChild method.

onClickChild(value){
   this.chat = value;
   this.count = this.count + 1;
}

Answer №2

There was an event added named "clicked", but it is recommended to use "click" instead.

<chat-compose @click="onClickChild"></chat-compose>

If you do want to create a "clicked" event, make sure to specify it within your chat-compose component.

Essentially, you will be receiving a custom component event and emitting a response or some action.

For custom component events:

https://v2.vuejs.org/v2/guide/components.html#Custom-Events https://v2.vuejs.org/v2/guide/components.html#Non-Parent-Child-Communication


If you intend to send a message to the parent, you can utilize:

this.$parent.chat = ...

or

You could also create a global event bus to centralize all events in one location (depending on the size/complexity of your application, this could be a good solution). More information about this approach can be found here: https://alligator.io/vuejs/global-event-bus/

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

Utilize jQuery to showcase images on your webpage

There seems to be an issue with image display - sometimes the selected image does not show up until clicked a second time. Using jQuery $('#morefiles').change(function (event) { if (!(/\.(gif|jpg|jpeg|tiff|png)$/i).test($(this).val())) { ...

Detecting errors in asynchronous functions within other asynchronous functions

I'm attempting to capture errors in nested asynchronous functions to perform a rollback if an error occurs. Initially, I have a try-catch block where I call a function that then calls another function. The final function should throw an error, and I ...

What is the best way to terminate a file upload initiated by ajaxSubmit() in jQuery?

A snippet of code I currently have is: UploadWidget.prototype.setup_form_handling = function() { var _upload_widget = this; $('form#uploader') .unbind('trigger-submit-form') // Possibly a custom method by our company . ...

Adding two comparable Objects in Javascript / vuejs

I have two objects and I want to add the values of each key separately with another object. Here's an example: CharacterStats: { a: 0, b: 2, c: 0, d: 0 } ItemStats: { a: 0, b: -1, c: 4, d: 0 } The expected result is: CharacterStats: { a: 0, b: 1, c: ...

Obtain the value of v-model in a child component within VueJS

In my Vuetify App, I have implemented a Vue2Editor using a custom component called text-editor. Here is how it looks: <vue-editor :value="text" @input="updateText" ></vue-editor> The props for this component are defined as follows: props ...

What steps can be taken to resolve the error message "t.onSubmit is not a function" that occurs upon form submission?

Upon submitting a form, it should trigger the onSubmit method function. However, an error is being returned instead: TypeError: "t.onSubmit is not a function". I've attempted to address this issue by researching similar problems and solutions provide ...

What is the correct way to show a JavaScript response on the screen?

Here is the JavaScript code I used to call the server API: <script type='text/javascript'> call_juvlon_api(apikey, 'getAvailableCredits', '', function(response) { document.getElementById('show').innerHT ...

Modify the conditions of a CSS file in Bootstrap using JavaScript

My project requires internationalization support for right-to-left languages like Arabic and Hebrew, so I need to modify some Bootstrap classes (such as col) to float right instead of left. I am using create-react-app with babel/webpack and react-bootstra ...

Tips for enhancing the color saturations of cells that overlap in an HTML table

My goal is to enhance the color of overlapping cells in my HTML tables. For instance, when I click on cell 2, the .nextAll(':lt(5)') method will change the class of the next 4 cells. https://i.stack.imgur.com/mwv8x.png Next, clicking on cell 3 ...

What could be the reason for my component not getting the asynchronous data?

Currently, I am delving into the intricacies of React and have been following a tutorial that covers creating components, passing props, setting state, and querying an API using useEffect(). Feeling confident in my understanding up to this point, I decided ...

Error: Attempting to retrieve a refresh token from the Google API resulted in an Uncaught ReferenceError, as the

I am currently working on obtaining a refresh token once a user authorizes with Google in order to prevent the need for re-authorization. After studying Google's documentation, I learned that setting the access type to offline is necessary. Now, I am ...

Displaying and Concealing Messages with VueJS

Currently, I have set up a basic CLI structure environment and created a component that displays messages/alerts such as "Login Failed." Since this component is intended to be reused throughout the entire app, I decided to import it into the root App.vue f ...

JavaScript Age Calculator - Counting Days

Hey there! I've got an interesting problem. I currently have three text boxes on my webpage, and what I want to achieve is having a fourth text box generated when the user clicks a button. The content of this new text box should be filled with the dat ...

Combining Two Tables Using jQuery

I am currently attempting to combine two tables into one using jQuery in the following manner: var table = document.createElement("table"); table.id = "mergedTable"; $("#mergedTable > tbody:last") .append($("#csvInfoTable2 > tbody").html()) ...

I'm having trouble sending registration emails through my server. What could be causing this issue?

Currently, I am in the process of developing a registration system that automatically sends an email with the user's username and password once they have successfully registered. The registration process functions smoothly up until the point where the ...

Using NextJS to navigate user journey by mapping an array of values from Formik to

I really appreciate all the help I've received so far, but I'm facing an issue trying to map an object with an array within it to the router. Here is my current code: const initialValues = { region: query.region || 'all', campt ...

Tips on building a carousel with slot elements

Many people have shown me the traditional way of creating a carousel using an array of images. However, I find this method to be limiting because I want each slide of my carousel to include a lightbox component. Instead of having to rewrite the lightbox fu ...

What is the method for incorporating parameters into an array filter?

Imagine having an array containing multiple duplicate objects. How can we create a condition to specifically identify objects with certain criteria, such as matching IDs, duplicate status, and duplicate dates? The goal is to only display the object with th ...

Using Javascript, populate an array with Enum variable values

Hey there! I've got this code that creates an array from an enum variable in JavaScript, but it's looking a bit old and clunky. I'm curious if any JavaScript or jQuery experts out there have a cleaner (best practice) approach for achieving ...

Is there a more efficient method to execute this AJAX request?

$('#request_song').autocomplete({ serviceUrl: '<%= ajax_path("trackName") %>', minChars:1, width: 300, delimiter: /(,|;)\s*/, deferRequestBy: 0, //miliseconds params: { artists: 'Yes' }, onSelect: functi ...