Carbon Charts-Svelte切换数据后阈值残留的响应式问题排查
双Y轴面积图切换阈值时旧阈值残留问题解决
问题
用Carbon Charts Svelte做了个双Y轴面积图,想根据后端返回的数据给其中一个Y轴加阈值。但切换数据或者切换阈值目标轴的时候,原来的阈值不会消失,最后两个Y轴都有各自的阈值,怎么都清不掉。
原因
原来的代码里,只有当alert.for匹配到对应轴时,才给轴加thresholds属性;不匹配的时候,这个属性根本没写。但Carbon Charts更新配置时,会保留之前没被覆盖的配置项,所以旧轴的阈值就一直留在那了。
解决办法
不管alert.for是不是当前轴,都显式给每个轴设置thresholds:匹配的时候放阈值数组,不匹配就放空数组(或者undefined),这样每次更新配置都会把旧阈值覆盖掉。
修改后的关键代码段:
$: options = { title: "What am I doing wrong?", axes: { bottom: { mapsTo: 'date', scaleType: ScaleTypes.TIME }, left: { title: 'Value 1', mapsTo: 'value1', // 显式设置thresholds,匹配时赋值,否则为空数组 thresholds: alert.for == 'value1' ? [ { value: alert.value, label: 'Alert 1', fillColor: 'red' } ] : [] }, right: { title: 'Value 2', mapsTo: 'value2', correspondingDatasets: ['Dataset 2'], // 右侧轴同理处理 thresholds: alert.for == 'value2' ? [ { value: alert.value, label: 'Alert 2', fillColor: 'green' } ] : [] } as ComboChartAxisOptions }, curve: 'curveNatural', height: '400px' } as AreaChartOptions;
完整可运行代码
<script lang="ts"> import '@carbon/charts-svelte/styles.css'; import { ScaleTypes, type AreaChart, type AreaChartOptions } from '@carbon/charts-svelte'; import { type ComboChartAxisOptions } from '@carbon/charts'; import { onMount, type ComponentType } from 'svelte'; let data = [ { group: 'Dataset 1', date: new Date(2019, 0, 1), value1: 0 }, { group: 'Dataset 1', date: new Date(2019, 0, 6), value1: -37312 }, { group: 'Dataset 1', date: new Date(2019, 0, 8), value1: -22392 }, { group: 'Dataset 1', date: new Date(2019, 0, 15), value1: -52576 }, { group: 'Dataset 1', date: new Date(2019, 0, 19), value1: 20135 }, { group: 'Dataset 2', date: new Date(2019, 0, 1), value2: 47263 }, { group: 'Dataset 2', date: new Date(2019, 0, 5), value2: 14178 }, { group: 'Dataset 2', date: new Date(2019, 0, 8), value2: 23094 }, { group: 'Dataset 2', date: new Date(2019, 0, 13), value2: 45281 }, { group: 'Dataset 2', date: new Date(2019, 0, 19), value2: -63954 } ] let alert = { for: "value1", value: 15000 } $: options = { title: "What am I doing wrong?", axes: { bottom: { mapsTo: 'date', scaleType: ScaleTypes.TIME }, left: { title: 'Value 1', mapsTo: 'value1', thresholds: alert.for == 'value1' ? [ { value: alert.value, label: 'Alert 1', fillColor: 'red' } ] : [] }, right: { title: 'Value 2', mapsTo: 'value2', correspondingDatasets: ['Dataset 2'], thresholds: alert.for == 'value2' ? [ { value: alert.value, label: 'Alert 2', fillColor: 'green' } ] : [] } as ComboChartAxisOptions }, curve: 'curveNatural', height: '400px' } as AreaChartOptions; let chart: ComponentType<AreaChart>; onMount(async () => { chart = (await import('@carbon/charts-svelte')).AreaChart; }); </script> <svelte:component this={chart} {options} {data} style="padding:2rem;" /> <button style="padding:1rem;" on:click={() => { alert.for = "value2" alert.value = -10000 }}>Click me to change the alert!</button>
额外提示
如果空数组[]没效果,可以试试把不匹配时的thresholds设为undefined,具体看Carbon Charts的配置处理逻辑。
内容的提问来源于stack exchange,提问作者LuMa
相关产品推荐
相关产品推荐

