Created
November 25, 2021 22:22
-
-
Save mpskovvang/44eabfd64994fede455c96a7fce033c1 to your computer and use it in GitHub Desktop.
Laravel Livewire with Chart.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Chart, LineController, LineElement, PointElement, LinearScale } from 'chart.js'; | |
Chart.register(LineController, LineElement, PointElement, LinearScale); | |
window.lineChart = () => { | |
return { | |
chart: null, | |
init() { | |
this.drawChart(this.$wire); | |
}, | |
drawChart(component) { | |
this.chart = new Chart(this.$refs.ctx, { | |
type: 'line', | |
data: component.get('data'), | |
options: { | |
scales: { | |
x: { | |
type: 'linear', | |
}, | |
y: { | |
type: 'linear', | |
} | |
} | |
} | |
}) | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<div | |
x-data="{ ...lineChart() }" | |
x-init="init()" | |
> | |
<canvas wire:ignore x-ref="ctx"></canvas> | |
</div> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Http\Livewire; | |
use Livewire\Component; | |
class LineChart extends Component | |
{ | |
public $data; | |
public function mount() | |
{ | |
$this->data = [ | |
'labels' => [1, 2, 3, 4, 5, 6, 7], | |
'datasets' => [ | |
[ | |
'label' => 'My First Dataset', | |
'data' => [65, 59, 80, 81, 56, 55, 40], | |
'tension' => 0.1, | |
] | |
] | |
]; | |
} | |
public function render() | |
{ | |
return view('livewire.line-chart'); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
A basic example to illustrate how to implement Chart.js in a Livewire project.
Typically, you would pass a data object or model to the component like
<livewire:line-chart :data="$data" />
. Alternately, you could extend the base class and load the data directly from the database or an external service.Styling could be achieved with:
Chart.defaults.line.borderWidth = 2;
).lineChart
component function.component.get('...')
.