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

What sets Angular 2 apart when it comes to utilizing [ngStyle] versus [style.attribute]?

When using Angular 2, what distinguishes the following 2 options for passing a variable value to a style? Are there advantages and disadvantages, or is it simply a matter of personal preference, or is one more adaptable/meant for specific purposes? Option ...

Setting up Vue and lint on run: what's involved in the configuration?

After running npm run serve, I encountered numerous warnings from a linter that I am struggling to locate and configure. Module Warning (from ./node_modules/eslint-loader/index.js): warning: Add a semicolon `;` (prettier/prettier) at src\main.js:1:22 ...

Checkbox inputs with activated labels causing double events to fire

Creating round checkboxes with tick marks dynamically and appending them to id="demo" on the click of two buttons that invoke the get(data) method is my current goal. The issue arises when both buttons are clicked simultaneously, as the checkboxes do not ...

Transforming every function into a for loop using jQuery

Previously, I sought help from the knowledgeable individuals on stackoverflow to assist me in shifting a background image the correct distance during a mouseover event. The solution worked smoothly, however, I am now pondering the efficiency of utilizing t ...

Save the click value for future use

My appointment form is divided into separate panels. At Step 1, if a user clicks on London (#Store1), I want to hide the Sunday and Monday options from the calendar in panel 5. Essentially, I need to save this click event so that when the user reaches th ...

Having trouble deleting multiple rows with ng-repeat in datatables

Having followed the instructions in this post, I quickly integrated it with jquery datatables. However, the functionality is not as expected. When attempting to delete rows, they do not get deleted. Furthermore, if I navigate to the next page and return, ...

Modifying the selected color of DropDownMenu List items

Hey there! I'm currently trying to modify the color of a material-ui element that is selected, but I'm having trouble finding any resources on how to accomplish this. My goal is to switch this pinkish shade to a more soothing blue hue. Update: I ...

React component closes onBlur event when clicked inside

I recently developed a React component using Material UI which looks like the code snippet below: <Popper open={open} anchorEl={anchorRef.current} onBlur={handleToggle} transition disablePortal > <MenuList autoFocusItem={open}> ...

Is there a way to change a model attribute in JSP based on the AJAX response?

I have a JSP page that contains the following code snippet: <li id="notifications"> <c:choose> <c:when test="${empty alerts}"> <p class="text-default">There are no Service Reminders at this time</p> ...

leveraging third party plugins to implement callbacks in TypeScript

When working with ajax calls in typical javascript, I have been using a specific pattern: myFunction() { var self = this; $.ajax({ // other options like url and stuff success: function () { self.someParsingFunction } } } In addition t ...

Tips for preventing unforeseen consequences in computed properties with VueJS

Currently, I am facing a challenge prefilling a form with data from a Vuex store. The code provided seems to give the expected result, but I am aware that this might not be the correct approach. My experience with Vue/Vuex is still limited. Since the input ...

What is the best way to extract information from my MYSQL database and represent it as an array?

Currently, I am working on a backend API that utilizes a MySQL database. My goal is to extract data from this database and utilize it to plot latitude and longitude points on a map using the Google Maps API. To achieve this, I have integrated the Gmaps API ...

How to achieve multiplication in Javascript without utilizing the * operand

Challenge 1 Criteria: This problem involves working with two positive integers N and M. Outcome: Upon completion, the function should output the result of multiplying N and M. For instance, if you input 5 and 8 into the function, it should calculate and ...

How can I utilize the Facebook API on Tizen to share a video?

Could someone please provide guidance on how to incorporate video uploading functionality into a Tizen application using the Facebook API and HTML5? ...

JS | How can we make an element with style=visibility:hidden become visible?

HTML: <div id="msg-text"><p><b id="msg" name="msg" style="visibility:hidden; color:#3399ff;">This is a hidden message</b></p></div> JS: $('#url').on('change keyup paste', function() { $('# ...

Click once to change the element, but it will remain changed and will not revert back no matter how many times you

After the first click displaying "X" and then changing to "O" in my tic-tac-toe JavaScript game, subsequent clicks only show "O", failing to switch back to "X". I am currently working on creating a tic-tac-toe game using JavaScript. Upon the first click, ...

Error Event Triggered by AJAX with No Response Data

I am currently facing an issue with an API call I am making. Everything seems to be working fine as I receive the token and a status code of 200 is returned (confirmed in Fiddler). However, the problem arises when the AjaxError event fires and the respon ...

Apply a border to the input field when the user enters or leaves the field, only if the value is

I am managing a few input fields and storing their information in an object. My goal is to click on an input field to focus on it, and if the field is empty or has a length greater than or equal to 0, I want it to display a red border. If I type somethin ...

It appears that you are utilizing the runtime-only version of Vue, which does not include the template compiler

When attempting to build my Vue.js application using webpack, a warning appears in the browser. The warning states: "You are using the runtime-only build of Vue where the template compiler is not available. Either pre-compile the templates into render f ...

Optimize your mobile experience by creating a notification menu that is scrollable and fixed in position

Recently, I purchased Moltran, but encountered a major issue: The notification menu disappears on mobile devices, which is not ideal for me. After some research, I discovered that removing the hidden-xs class from the li notification element can solve this ...