javascriptvue.jsparent-childpull-to-refresh

Vue.js parent don't send updated data to child


I can't update data in child from parent. Parent sends only initial data, but if I update data by function, then I fetch it from Back-end, nothing changed. I even made wacher, it works then data changed (write debug word in console) but still not sending updated data. How I should use dynamicly changed data to refresh child from parent data?

Parent:

<el-date-picker
    v-model="reportMonth"
    type="month"
    format="MMMM yyyy"
    value-format="yyyy-MM-dd"
    placeholder="Choose month"
    @change="generateReport">
  </el-date-picker>

<bar-chart :parent-data="sendData"></bar-chart>

data() {
    return {
      monthData: null,
      sendData: {
        lowRiskPreliminary: 0,
        midRiskPreliminary: 0,
        highRiskPreliminary: 0,
        inadmissibleRiskPreliminary: 0,
        notValidPreliminary: 0
      }


watch: {
    monthData: function() {
      console.log('data changed!')
      this.sendData = this.monthData
    }
  },
  methods: {
    generateReport() {
      this.listLoading = true
      getMonthlyReport(this.reportMonth).then(response => {
        this.monthData = response.data }

Child:

<template>
  <div :class="className" :style="{height:height,width:width}"></div>
</template>

export default {
  props: {
    className: {
      type: String,
      default: 'chart'
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '300px'
    },
    parentData: {
      type: Object,
      default: undefined
    }
  },
  data() {
    return {
      chart: null,
      lowRisk: [this.parentData.lowRiskPreliminary],
      midRisk: [this.parentData.midRiskPreliminary],
      highRisk: [this.parentData.highRiskPreliminary],
      inhRish: [this.parentData.inadmissibleRiskPreliminary],
      notVal: [this.parentData.notValidPreliminary]
    }
  },
  mounted() {
    this.initChart()

methods: {
    initChart() {
      this.chart = echarts.init(this.$el)
      this.chart.setOption({

Solution

  • You have primitive value undefined as default for parentData, and you change it to object after updating parent variable. See more about reactivity in VueJS and caveats: https://v2.vuejs.org/v2/guide/reactivity.html

    Use $nextTick:

    watch: {
         monthData: function() {
           this.$nextTick(function () {
               this.sendData = this.monthData
           })
        }
    }
    

    or use $emit, to emit event from parent:

    watch: {
        monthData: function() {
       
               this.$emit('monthDataUpdated', this.monthData);
        }
    }
    

    and in child:

    events: {
       'monthDataUpdated' : function(data){
         this.$nextTick(function () {
           this.parentData = data;
         });
       },
    }