const config = {
type: "bar",
data: {
labels: [
"Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
],
datasets: [
{
label: "Html Template",
maxBarThickness: 12,
data: [60, 150, 30, 200, 180, 50, 180, 120, 230, 180, 250, 270],
backgroundColor: () => getColor("--color-primary", 0.3),
borderColor: () => getColor("--color-primary"),
borderWidth: 1,
},
],
},
options: {
maintainAspectRatio: false,
plugins: { legend: { display: false } },
scales: { x: { display: false }, y: { display: false } },
},
};
<Chart class="max-w-100 h-64" :config="config" />
npx @left4code/cosmic-ui-cli@latest add chart
This writes the component and everything it imports, then installs the packages it needs. Run npx @left4code/cosmic-ui-cli@latest initfirst if you haven't already (it detects Vue automatically).
Install the following dependencies:
Or copy and paste the code below by hand.
<script lang="ts">
function getColor(name: string, opacity = 1) {
const color = getComputedStyle(document.documentElement).getPropertyValue(name).trim();
if (opacity < 1) {
return `color-mix(in oklch, ${color} ${opacity * 100}%, transparent ${
100 - opacity * 100
}%)`;
}
return color;
}
export { getColor };
</script>
<script setup lang="ts">
import { ref, onMounted } from "vue";
import ChartJs from "chart.js/auto";
import { twMerge } from "tailwind-merge";
const props = defineProps<{
class?: string;
config: ConstructorParameters<typeof ChartJs>[1];
}>();
const canvasRef = ref<(HTMLCanvasElement & { instance?: unknown }) | null>(null);
onMounted(() => {
if (canvasRef.value && !canvasRef.value.instance) {
canvasRef.value.instance = new ChartJs(canvasRef.value, props.config);
}
});
</script>
<template>
<div :class="twMerge('relative h-full w-full', props.class)">
<canvas ref="canvasRef" />
</div>
</template>
Update the import paths to match your project setup.
import Chart, { getColor } from "@/components/ui/chart.vue";
const config = {
type: "bar",
data: {
labels: [
"Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
],
datasets: [
{
label: "Html Template",
maxBarThickness: 12,
data: [60, 150, 30, 200, 180, 50, 180, 120, 230, 180, 250, 270],
backgroundColor: () => getColor("--color-primary", 0.3),
borderColor: () => getColor("--color-primary"),
borderWidth: 1,
},
],
},
options: {
maintainAspectRatio: false,
plugins: { legend: { display: false } },
scales: { x: { display: false }, y: { display: false } },
},
};
<Chart class="max-w-100 h-64" :config="config" />