i'm having troubles with passing data to the function myChart, in the mounted part. I'm new in vuejs and having some difficulties in understanding whats wrong. i want to pass data in labels and datasets, which are called from mine function. Anyone can help? Thanks in advance the code:
<script>
import Chart from 'chart.js';
export default {
data() {
return {
tests:[]
};
},
created(){
this.mine();
},
methods: {
mine(){
let self = this;
this.$http.get('tests/mine').then(response=>{
self.tests = response.data.tests;
}).then(error=>{
console.log(error) ;
});
}},
mounted() {
var self=this;
var ctx = document.getElementById("weightchart");
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: test.dt_test,
datasets: [{
label: 'weight',
data: test.weight,
backgroundColor: [
'rgba(255, 255, 255, 0)',
'rgba(255, 255, 255, 0)',
'rgba(255, 255, 255, 0)',
'rgba(255, 255, 255, 0)',
'rgba(255, 255, 255, 0)',
'rgba(255, 255, 255, 0)'
],
borderColor: [
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero:true
}
}]
}
}
});
},
computed: {},
watch: {}
}
</script>
Instead of creating another function for asynchronous call you could add get call inside mounted and in its return in .then() function create your chart and perform other operations.
Other way could be you return promise object from the method and then on its .done() method you could write your mounted code logic.
Your code is fine. What is happening here your code is finished executing before you get the data from the server. When you are calling the methods mine(), it is sending HTTP request asynchronously. But your Vue code does't wait for the response it will get. Instead it continues running the rest of the script. By the time you get the response from the server, Vue already initialized your chart with the blank data.
So you have to make sure you initialize your chart after you successfully get the data from the server. Put the initialization code within a method and call that method after you get the data from the server --
this.$http.get('tests/mine').then(response=>{
self.tests = response.data.tests;
// initialize your chart here, like -
// this.initChart();
}.bind(this)).then(error=>{
console.log(error) ;
});