英文:
how to loop through data in vuejs
问题
这是我的数据库架构:
这是组件模板:
<template>
<div>
<div id="chart"></div>
<div v-for="revenue in revenues" :key="revenue._id">
{{ revenue.income }}
</div>
{{ revenues }}
</div>
</template>
<script>
import ApexCharts from 'apexcharts';
import axios from "axios";
export default {
data(){
return{
revenues: ""
};
},
mounted() {
axios
.get(`http://localhost:5000/api/revenue`, {})
.then(response => {
this.revenues = response.data.revenues;
})
.catch(error => {
});
// 这是硬编码数据,用于显示图表
var options = {
series: [{
name: 'series1',
data: [31]
}, {
name: 'series2',
data: [11]
}],
chart: {
height: 350,
type: 'area'
},
xaxis: {
type: 'datetime',
categories: ["2018-09-19T00:00:00.000Z",]
},
};
var chart = new ApexCharts(document.querySelector("#chart"), options);
chart.render();
},
};
</script>
如何在我的 var options
数据中输入 revenue.income
?
英文:
This is my database schema :
This is the component template :
<template>
<div>
<div id="chart"></div>
<div v-for="revenue in revenues" :key="revenue._id">
{{revenue.income}}
</div>
{{revenues}}
</div>
</template>
<script>
import ApexCharts from 'apexcharts';
import axios from "axios"
export default {
data(){
return{
revenues:""
};
},
mounted() {
axios
.get(`http://localhost:5000/api/revenue`, {})
.then(response => {
this.revenues = response.data.revenues;
})
.catch(error => {
});
// this is the harcoded data which displays chart
var options = {
series: [{
name: 'series1',
data: [31]
}, {
name: 'series2',
data: [11]
}],
chart: {
height: 350,
type: 'area'
},
xaxis: {
type: 'datetime',
categories: ["2018-09-19T00:00:00.000Z",]
},
};
var chart = new ApexCharts(document.querySelector("#chart"), options);
chart.render();
},
};
</script>
How can I loop through this data instead of inputing hard coded numbers, this is my json that displays in my broswer.
How can I input revenue.income in my var option data ?
答案1
得分: 2
你只需更新代码中的 "then" 块,将要渲染的所有数据添加到 "options.series" 数组的 "data" 属性中。目前,我已添加了收入和支出。
我建议你创建一个单独的方法来处理这个逻辑,并在 "then" 块内调用它。
英文:
You just have to update your then block in the code
axios
.get(`http://localhost:5000/api/revenue`, {})
.then(response => {
this.revenues = response.data.revenues;
const options = {
series: [],
chart: {
height: 350,
type: 'area'
},
xaxis: {
type: 'datetime',
categories: ["2018-09-19T00:00:00.000Z",]
},
}
this.revenues.forEach(revenue => {
options.series.push({ name: revenue.time, data: [revenue.income, revenue.expenses] })
});
var chart = new ApexCharts(document.querySelector("#chart"), options);
chart.render();
}).catch(error => {
console.error('Error', error)
});
In above code add all the data you want to render in data
property of options.series array, right now I have added income and expenses.
I suggest you to create seperate method for this logic and call it inside the then block.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论