在Svelte组件中显示星流图


<script lang="ts">
import { onMount } from 'svelte';
import { Chart } from 'frappe-charts';
let chartElem;
const chartData = {
labels: ["12am-3am", "3am-6pm", "6am-9am", "9am-12am",
"12pm-3pm", "3pm-6pm", "6pm-9pm", "9am-12am"
],
datasets: [
{
name: "Some Data", type: "bar",
values: [25, 40, 30, 35, 8, 52, 17, -4]
},
{
name: "Another Set", type: "line",
values: [25, 50, -10, 15, 18, 32, 27, 14]
}
]
};
onMount(() => {
console.log(chartElem); // always undefined... why??
new Chart({
parent: chartElem,
title: "My Awesome Chart",
data: chartData,
type: 'axis-mixed', // or 'bar', 'line', 'scatter', 'pie', 'percentage'
height: 250,
colors: ['#7cd6fd', '#743ee2']
});
});
<div bind:this={chartElem}>loading chart...</div>

我试图在我的Svelte组件中绘制图表,上面是我当前的代码。根据Svelte文档,bind:this是引用dom节点chartElem的方式,以便在组件代码中我可以在div上绘制图表。

但不知何故,我一直得到undefined与我的chartElem变量。我哪里做错了?或者也许我需要一个不同的图表库,而不是星冰图?

冰冻过的图

苗条的绑定:

看起来我实例化Frappe Chart对象的方式可能是错误的。我对原始代码做了一些调整。

<script lang="ts">
import { onMount, onDestroy } from 'svelte';
import { Chart } from 'frappe-charts';
let chartElem;
let chart
const chartData = {
labels: ["12am-3am", "3am-6pm", "6am-9am", "9am-12am",
"12pm-3pm", "3pm-6pm", "6pm-9pm", "9am-12am"
],
datasets: [
{
name: "Some Data", type: "bar",
values: [25, 40, 30, 35, 8, 52, 17, -4]
},
{
name: "Another Set", type: "line",
values: [25, 50, -10, 15, 18, 32, 27, 14]
}
]
};
onMount(() => {
chart = new Chart(chartElem, {
title: "My Awesome Chart",
data: chartData,
type: 'axis-mixed', // or 'bar', 'line', 'scatter', 'pie', 'percentage'
height: 250,
colors: ['#7cd6fd', '#743ee2']
});
});
onDestroy(() => {
chart = null;
});
<div bind:this="{chartElem}"></div>

这对我很有用。

同样,值得注册onDestroy生命周期方法,以便图表对象可以被正确地清理。

相关内容

  • 没有找到相关文章

最新更新