![](/img/trans.png)
[英]Vue.js child component with object literals as props unexpectedly updates when its parent renders
[英]Vue.js not updating props in child when parent component is changing the property
我正在嘗試在具有類似結構的組件之間進行通信
<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>
父母
methods: {
onClickChild (value) {
console.log('in top parent');
this.chat = value;
},
孩子 1
methods: {
startChat: function(event) {
this.$emit('clicked', new chat({
type: 'user',
message: this.input_value,
button: 'user',
metaInfo: 'user',
isBot: false,
}))
},
},
孩子 2
導出默認{名稱:'messageContainer',道具:['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)
}
}
在這里,clickChild 方法發出父方法,該方法正在更新聊天對象,但消息容器組件沒有獲得更新的值,它顯示默認的初始化值,甚至沒有再次呈現我嘗試創建、安裝和更新的數據更改方法來獲取更新值這些方法在應用程序初始化時僅調用一次,從不再次調用數據更改
基本上這里有三個組件,一個是父級,另外兩個是子級,所以一個子級正在更新聊天對象並發送給父級,父級將相同的更新后的子級傳遞給另一個子級,但另一個子級沒有重新渲染或獲取更新的值,所以請幫助我做錯了還是有其他方法可以實現它。
這可能是由於 Vue 緩存了<message-container>
組件。
嘗試添加 :key 組件以強制它重新渲染。
<message-container :chat="chat" :key="count"></message-container>
為您的onClickChild
方法添加一個計數器
onClickChild(value){
this.chat = value;
this.count = this.count + 1;
}
您添加了一個名為“clicked”的事件。 您應該改用“點擊”。
<chat-compose @click="onClickChild"></chat-compose>
如果你想創建“點擊”事件,你需要在你的聊天撰寫組件中指定它。
基本上,您將收到一個自定義組件事件並發出一個響應/某事。
https://v2.vuejs.org/v2/guide/components.html#Custom-Events https://v2.vuejs.org/v2/guide/components.html#Non-Parent-Child-Communication
如果要向父母發送消息,可以使用:
this.$parent.chat = ...
或者
創建一個全局事件總線,將所有事件保存在一個地方(取決於應用程序的大小/復雜性,這可能是一個很好的解決方案)。 你可以在這里閱讀: https ://alligator.io/vuejs/global-event-bus/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.