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

查看:168
本文介绍了javascript - 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

这篇关于javascript - Vue 父组件ajax异步更新数据,子组件获取不到的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆