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