Need help with Inertia/Vue frontend
I've worked with Laravel and Livewire, but I'm currently working on a test project to learn Vue, along with Inertia and Tailwind. Currently I'm stuck on the frontend part of it, where I want to fetch data from an ApiController to feed a ChartJS graph. I'm currently stuck on error messages like " 'this' is undefined" in my vue code, so I'm looking for the right way to attach response data to props.
Originally I had the Eloquent query in the AccountsController, and when I passed the labels and chartData from the AccountsController to the Vue file through Inertia it worked fine. But now that I want to fetch the content dynamically, I get stuck on how to fetch / assign the variables/props.
Also my iDE gives me some warnings about the two statements in the .then() statement, and trying to split them with semicolons doesn't seem to help.
Any help and feedback is welcome :)
//AccountController@showDashboard()
public function showDashboard()
{
return Inertia::render('Dashboard', [
'accounts' => User::query()->where('id', Auth::user()->getAuthIdentifier())->first()->accounts,
]);
}
//Dashboard.vue
<script setup>
import AppLayout from '@/Layouts/AppLayout.vue';
import { onMounted } from 'vue';
import Chart from 'chart.js/auto';
const props = defineProps({
accounts: {
type: Array
}
});
onMounted(() => {
const chartElement = document.getElementById('myChart');
const myChart = new Chart(chartElement, {
type: 'line',
data: {
labels: data.labels,
datasets: data.datasets
},
options: {
scales: {
y: {
beginAtZero: true
}
}
}
});
})
</script>
<template>
[...]
</template>
export default {
name: "Dashboard.vue",
methods: {
fetch() {
axios
.post('http://financer.test/api/getAccountFlow', {
accounts: this.selectedAccount,
})
.then(response => (
this.datasets.data = response.chartData,
this.labels.data = response.labels
))
},
updateAccounts(event) {
this.selectedAccount = [event.target.value];
this.fetch()
},
},
data () {
return {
datasets: [],
labels: [],
selectedAccount: '',
}
},
mounted () {
this.fetch()
}
}
</script>
//ApiController
public function getAccountFlow(){
[Eloquent query to create $chartDatasets]
return json_encode([
'labels' => $labels,
'chartData' => $chartDatasets
]);
}
Please or to participate in this conversation.