Vue 父组件ajax异步更新数据,子组件获取不到

Vue父组件ajax异步获取数据以后绑定子组件,但子组件内获取不到数据
父组件template:
<card-line1-chart-example class="chart-wrapper px-10" v-if="line1data" style="height:230px;" :lineone="line1data" height="70"/>
js:

import { dropdown } from 'vue-strap'
import CardLine1ChartExample from './dashboard/CardLine1ChartExample'
import CardLine2ChartExample from './dashboard/CardLine2ChartExample'
import CardLine3ChartExample from './dashboard/CardLine3ChartExample'
export default {
  name: 'dashboard',
  components: {
    dropdown,
    CardLine1ChartExample,
    CardLine2ChartExample,
    CardLine3ChartExample
  },
  data () {
    return {
      line1data: []
    }
  },
  mounted () {
    var self = this
    this.$ajax.get('http://xx.com/?action=getIndex').then(function (response) {
      self.line1data = response.data.Facebook
      console.log(1111)
    }).catch(function (error) {
      console.log(error)
    })
  }
}

子组件:

<script>
import { Line } from 'vue-chartjs'

export default Line.extend({
  props: ['height', 'lineone'],
  mounted () {
    console.log(222)
    console.log(this.lineone)
    this.renderChart({
      labels: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23'],
      datasets: this.lineone
    }, {
      maintainAspectRatio: false
    })
  }
})
</script>

一开始搜索的问题,v-if并不能解决当前问题,是不是跟ajax异步有关系

回答:

子组件钩子mounted应该在刚开始页面渲染时候执行一次,执行的时候如果你的父组件异步请求还未执行回调,子组件mounted获取不到值的,正确的做法是在子组件里面使用watch监听lineone,如果lineone改变后即可更新renderChart

回答:

v-if="line1data.length"

回答:

mounted的时候父组件的ajax还没有返回数据吧
而且mounted只会执行一次,就算数据后面改变了,mounted里面的也不会再次执行
试一下watch那个lineone,然后再去调用this.renderChart

回答:

辛苦千年老妖 & Jer_994 不能采纳多条,忘见谅
<script>
import { Line } from ‘vue-chartjs’

export default Line.extend({
props: [‘height’, ‘lineone’],
watch: {

lineone: function () {
  this.renderChart({
    labels: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23'],
    datasets: this.lineone
  }, {
    maintainAspectRatio: false
  })
}

}
})
</script>
最后通过watch 完成更新、

暂无评论

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注