我修改了一个apexcharts Vue组件BarChart。Vue来自https://github.com/apexcharts/vue3-apexcharts
我想通过使用REST GET API检索图表数据,并将数据插入series
。
该组件的脚本部分如下;
<script>
/* eslint-disable */
export default {
name: "BarExample",
data: dataInitialisation,
methods: {
updateChart,
},
};
async function makeGetRequest(url) {
const axios = require("axios");
//let res = await axios.get("http://localhost:8080/vue3-apexcharts/data.json");
let res = await axios.get(url);
return res.data;
}
function dataInitialisation() {
let init_data = {
chartOptions: {
chart: {
type: "bar",
stacked: true,
animations: {
enabled: true, //disabling will speed up loading
},
},
},
series: {},
};
var url = "http://localhost:8080/vue3-apexcharts/data.json";
const axios = require("axios");
var data;
makeGetRequest(url).then(
(data) =>
{
console.log(JSON.stringify(data));
init_data.series = data;
}
);
return init_data;
}
我验证了通过使用console.log()
打印数据从REST GET获取数据的代码没有任何错误。
我做了一些研究,似乎我需要使用mounted()
来获得数据出现在图表上。如果这是正确的,我如何修改代码使用mounted()
这样做?
我使用的值是3
几件事
永远不要在Vue组件的Vue api之外定义函数和逻辑。在data
中定义的内容应该在data
中定义,您将遇到的每个文档都以相同的方式进行定义。数据属性和方法。
回答你的问题是的,当组件挂载时,你需要一个生命周期钩子从api中获取数据,你可以在这篇文章中阅读更多关于生命周期钩子的内容
// From this line until the end just delete everything.
// Define `methods` and `data` where they belong.
function dataInitialisation() {
let init_data = {
chartOptions: {
下面是一个重构的例子:<script>
import axios from 'axios'
export default {
name: 'BarExample',
data() {
return {
url: 'http://localhost:8080/vue3-apexcharts/data.json',
chartOptions: {
chart: {
type: 'bar',
stacked: true,
animations: {
enabled: true
}
}
},
series: {}
}
},
async mounted() {
await this.makeGetRequest()
},
methods: {
updateChart, // Where is this method defined?
async makeGetRequest() {
const { data } = await axios.get(this.url)
this.series = data
}
}
}
</script>
我将回答我自己的问题。答案的关键来自vue-apexcharts库中可用的挂载事件。
https://apexcharts.com/docs/options/chart/events/
我将本文用作如何在ve3 -apexcharts中使用事件的指南。
https://kim-jangwook.medium.com/how-to-use-events-on-vue3-apexcharts-2d76928f4abc
<template>
<div class="example">
<apexchart
width="500"
height="350"
type="bar"
:options="chartOptions"
:series="series"
@mounted="mounted"
></apexchart>
</div>
</template>
<script>
async function makeGetRequest(url) {
const axios = require("axios");
//let res = await axios.get("http://localhost:8080/vue3-apexcharts/data.json");
let res = await axios.get(url);
return res.data;
}
export default {
name: "BarExample",
data: dataInitialisation,
methods: {
updateChart,
mounted: function(event, chartContext, config) {
console.log("mount event");
var url = "http://localhost:8080/vue3-apexcharts/data.json";
const axios = require("axios");
var data;
makeGetRequest(url).then((data) => {
this.series = data;
});
},
},
};
</script>