【发布时间】:2020-08-07 14:37:18
【问题描述】:
vue 组件使用 axios get 不会等待控制器的数据,它会提示错误:
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>
我必须使用watch方法吗?
【问题讨论】:
-
请分享您的代码
-
使用 v-if 和 v-else 来决定是否显示组件。我在从服务器检索数据之前显示了一个加载组件
-
您正在使用没有等待的异步,但不是这里的问题。 console.log 打印什么?
-
当 console.log "data[i]['ftth']" 它说 "index.vue?d4c7:207 Uncaught (in promise) TypeError: Cannot read property 'ftth' of undefined at eval ”。也许是因为我在控制器中使用了 foreach,这就是为什么将数据传递给 vue 需要时间?
-
@Savlon,经过大量调试。谢谢你的帮助:) 我也用 axios 超时。
标签: laravel vue.js vue-component