如何让Vue组件等待数据准备好渲染? [英] How to let vue component wait until the data is ready for render?
本文介绍了如何让Vue组件等待数据准备好渲染?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
vue组件不会等待使用axios get从控制器获取数据,它会提示错误:
vue component won't wait for data from controller using axios get, it prompt error:
index.vue?d4c7:200未捕获(已承诺)TypeError:无法读取未定义的属性'ftth'
index.vue?d4c7:200 Uncaught (in promise) TypeError: Cannot read property 'ftth' of undefined
我的代码如下:
<template>
<div class="dashboard-editor-container">
<el-row style="background:#fff;padding:16px 16px 0;margin-bottom:32px;">
<line-chart :chart-data="lineChartData"/>
</el-row>
</div>
</template>
<script>
import LineChart from './components/LineChart';
import axios from 'axios';
const lineChartData = {
all: {
FTTHData: [],
VDSLData: [],
ADSLData: [],
},
};
export default {
name: 'Dashboard',
components: {
LineChart,
},
data() {
return {
lineChartData: lineChartData.all,
};
},
created() {
this.getData();
},
methods: {
handleSetLineChartData(type) {
this.lineChartData = lineChartData[type];
},
async getData() {
axios
.get('/api/data_graphs')
.then(response => {
console.log(response.data);
var data = response.data;
var i = 0;
for (i = Object.keys(data).length - 1; i >= 0; i--) {
lineChartData.all.FTTHData.push(data[i]['ftth']);
lineChartData.all.VDSLData.push(data[i]['vdsl']);
lineChartData.all.ADSLData.push(data[i]['adsl']);
}
});
},
},
};
</script>
我必须使用监视方法吗?
Do I have to use watch method?
推荐答案
首先,由于您具有这样的嵌套数据结构,因此您需要一个计算属性来返回是否加载数据.通常,您可以在模板中执行此检查.
First, because you have such a nested data structure you'll want a computed property to return whether the data is loaded or not. Normally, you could do this check in the template.
computed: {
isDataLoaded() {
const nestedLoaded = Object.keys(this.lineChartData).map(key => this.lineChartData[key].length !== 0)
return this.lineChartData && nestedLoaded.length !== 0
}
}
您可以使用 v-if ="isDataLoaded"
隐藏元素,直到数据加载完毕.
You can use v-if="isDataLoaded"
to hide the element until the data has been loaded.
这篇关于如何让Vue组件等待数据准备好渲染?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文