Instalação passo a passo
Este guia parte do pressuposto que já existe uma aplicação com Laravel e Vue. Caso ainda não tenha a aplicação, recomendo a leitura do artigo Laravel com Inertia e Vue.
Instalar o plugin Chart
Instalar com o NPM:
npm i vue-chartjs chart.js
Lembrar-se de atualizar os assets:
npm run dev
Criação do componente
Os componentes podem ficar na pasta:
/resources
+- /js
+- /Components
Crie o componente genérico para o LineChart:
<script setup>
import { Line } from 'vue-chartjs'
import {
Chart as ChartJS,
CategoryScale,
LinearScale,
PointElement,
LineElement,
Title,
Tooltip,
Legend
} from 'chart.js'
ChartJS.register(
CategoryScale,
LinearScale,
PointElement,
LineElement,
Title,
Tooltip,
Legend
)
const props = defineProps({
title: {
type: String,
default: 'Chart'
},
chartData: {
type: Object,
required: true
},
chartOptions: {
type: Object,
default: () => ({
responsive: true,
maintainAspectRatio: false,
})
}
})
</script>
<template>
<div class="p-6 bg-white rounded-lg shadow-lg">
<h2 class="text-xl font-semibold mb-4">{{ title }}</h2>
<Line
v-if="chartData"
:data="chartData"
:options="chartOptions"
/>
</div>
</template>
Chamada ao componente
Através da página pelo Controller:
public function index()
{
$chartData = [
'labels' => ['January', 'February', 'March', 'April', 'May', 'June'],
'datasets' => [
[
'label' => 'Sales 2024',
'data' => [65, 59, 80, 81, 56, 55],
'fill' => false,
'borderColor' => 'rgb(75, 192, 192)',
'tension' => 0.1
]
]
];
return Inertia::render('Dashboard', [
'chartData' => $chartData
]);
}
Chamada da página ao Componente Vue:
<!-- resources/js/Pages/Dashboard.vue -->
<template>
<AppLayout title="Dashboard">
<template #header>
<h2 class="font-semibold text-xl text-gray-800 leading-tight">
Dashboard
</h2>
</template>
<div class="py-12">
<div class="max-w-7xl mx-auto sm:px-6 lg:px-8">
<div class="bg-white overflow-hidden shadow-sm sm:rounded-lg">
<LineChart
title="Monthly Sales"
:chart-data="props.chartData"
/>
</div>
</div>
</div>
</AppLayout>
</template>
<script setup>
import { defineProps } from 'vue'
import AppLayout from '@/Layouts/AppLayout.vue'
import LineChart from '@/Components/LineChart.vue'
const props = defineProps({
chartData: {
type: Object,
required: true
}
})
</script>