[Vuejs]-Updating a data object that gets passed around Vue components

0👍

✅

if a parent component has multiple child ones, it can pass data to them using props and any change in the parent component of that data affects automatically the passed data, let’s suppose we have a parent component which contains two numbers and there’s two child components, one calculates the sum and another one for multiplying them :

Vue.component('sum', { 
props:["n1","n2"],
template:'<div>Sum => <h3>{{n1+n2}}</h3></div>'

})

Vue.component('mult', { 
props:["n1","n2"],
template:'<div>Mult => <h3>{{n1*n2}}</h3></div>'

})

new Vue({
  el: '#app',
data:{
      num1:0,
      num2:0       
     } 
})
<link type="text/css" rel="stylesheet" href="//unpkg.com/bootstrap/dist/css/bootstrap.min.css"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js"></script>

<div id="app">
     <input type="number" v-model.number.lazy="num1" class="form-control">
      <input type="number" v-model.number.lazy="num2" class="form-control">
     <span>Parent => ({{num1}},{{num2}})</span>
     <sum :n1="num1" :n2="num2"></sum>
    <mult :n1="num1" :n2="num2"></mult>
</div>

it’s a very basic example but it shows the use and the utility of that hierarchy, and the v-model directive is very useful when we work with forms and inputs

Leave a comment