I'm fairly new to Vue Framework and I'm trying to figure out how to update a child component based on changes in the parent component's attributes. In the code snippet below, I've created a component that displays a greeting message based on the "name" attribute of the node passed from the parent.
Everything works fine if the "name" attribute is present when the node is initialized. However, if the name attribute is added later (as shown in the demonstration with a setTimeout function), the component throws an error and doesn't reflect the changes. I'm struggling to understand how to propagate changes for dynamic attributes generated outside the component.
Essentially, I want the component to dynamically display different widgets based on server responses tied to properties passed to it. I want the component to update itself whenever these properties change. Why isn't two-way binding working as expected in Vuejs?
Vue.component('greeting', {
template: '#treeContainer',
props: {'message':Object},
watch:{
'message': {
handler: function(val) {
console.log('###### changed');
},
deep: true
}
}
});
var data = {
note: 'My Tree',
// name:"Hello World",
children: [
{ name: 'hello' },
{ name: 'wat' }
]
}
function delayedUpdate() {
data.name='Changed World';
console.log(JSON.stringify(data));
}
var vm = new Vue({
el: '#app',
data:{
msg:data
},
method:{ }
});
setTimeout(function(){ delayedUpdate() ;}, 1000)
<script src="https://vuejs.org/js/vue.js"></script>
<div id="app">
<greeting :message="msg"></greeting>
</div>
<script type="text/x-template" id="treeContainer">
<h1>{{message.name}}</h1>
</script>
Edit 1: @Craig's answer helped me understand how to propagate changes using the "name" attribute and calling set on each attribute. But what if the data is complex and the greeting message relies on multiple attributes of the node? In real-world scenarios, widgets are based on many dynamically sent attributes from the server and each widget varies based on its type. For example, "Welcome, {{message.name}} . Temperature at {{ message.location }} is {{ message.temp}} ." Since the attributes can vary, is there a way to update the entire tree without manually traversing all nodes and calling set on each attribute? Does VUE framework offer a solution for this situation?