blackCrow
blackCrow

Reputation: 13

Child component not update value from Parent

I am new vue js. I don't know why value in child component not update when I change value in parent component. Can anyone explain for me? I know that I can use Times Updated: {{ times}} to display. But I want to assign it into count to do something else

Parent HTML

<div id="test">
  <button @click="clicktime">Click</button>
  <times-updated :times.sync="myData"></times-updated>
</div>

.js file

var vm = new Vue({
  el: '#test',
  data(){
    return {
      myData: 100
    }
  },

  methods: {
    clicktime() {
      vm.myData = Math.random();
    }
  }
})

Child

Vue.component('times-updated', {
  props:["times"],
  data() {
    return {
      count: this.times
  }
},
  template: '<span>Times Updated: {{ count }}</span>',
});

link codepen: enter link description here

Upvotes: 1

Views: 81

Answers (2)

Niklesh Raut
Niklesh Raut

Reputation: 34924

You need computed data instead data element, which keep watch and updates

Vue.component('times-updated', {
  props:["times"],
  computed: {
    count: function(){
       return this.times;
    }
  },
  template: '<span>Times Updated: {{count}}</span>',
});

var vm = new Vue({
  el: '#test',
  data(){
    return {
      myData: 100
    }
  },

  methods: {
    clicktime() {
      vm.myData = Math.random();
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.10/vue.js"></script>
<div id="test">
  <button @click="clicktime">Click</button>
  <times-updated :times.sync="myData"></times-updated>
</div>

Upvotes: 1

Flink
Flink

Reputation: 1006

In the child you can use your prop value directly, then it'll work:

Vue.component('times-updated', {
  props:["times"],
  data() {
    return {
      count: this.times // not needed, not reactive
  }
},
  template: '<span>Times Updated: {{ this.times }}</span>',
});

Upvotes: 0

Related Questions