rubie
rubie

Reputation: 67

I want to watch to the value of the parent component in the child component

In this code, console isn't work

child component

props: {
    tab: ''
},
data: function () {
    return 
        tabs: this.tab,
    };
},
watch: {
     tabs: function () {
         console.log('tabs', this.tabs);
     },
},

parent component

<table
    :tab="0">
</table>

Upvotes: 0

Views: 1319

Answers (2)

Amaarockz
Amaarockz

Reputation: 4684

An alternate approach

props: {
    tab: {
    type: Number,
    default: 0
  }
},
data() {
    return {
        tabs: this.tab,
    };
},
watch: {
     tab(newVal) {
         this.tabs = newVal;
         console.log('tabs', newVal);
     },
},

Upvotes: 0

Boussadjra Brahim
Boussadjra Brahim

Reputation: 1

in

data: function () {
    return 
        tabs: this.tab,
    };
},

the tabs property takes only the initial value, I recommend to use a computed property instead of data :

props: {
    tab: ''
},
computed:{
    tabs(){
     return this.tab;
   }
},
watch: {
     tabs: function () {
         console.log('tabs', this.tabs);
     },
},

or you could watch the prop directly :

props: {
    tab: ''
},

watch: {
     tab: function () {
         console.log('tab', this.tab);
     },
},

Note that you shouldn't use HTML native elements as vue component like table

if the prop is an object or an array you should add deep option like :

props: {
    tab: ''
},
computed:{
    tabs(){
     return this.tab;
   }
},
watch: {
     tabs:{
      handler: function () {
         console.log('tabs', this.tabs);
     },
    deep:true
    }
},

Upvotes: 1

Related Questions