I have a JavaScript file which contains the data of a chart, I want that chart to be displayed in a Vue component, but how can I do that.
Javascript file named as LineChart.js
new Vue({
data: () => ({
date: [
1600934100.0,
1602009600.0,
1602747060.0,
1603050158.390939,
1603305573.992575
],
challenge: [
9.0,
9.5,
2.5,
11.52,
12.4
]
}),
mounted() {
let data = this.date.map((date, index) => ({
x: new Date(date * 1000),
y: this.challenge[index]
}))
let ctx = this.$refs.chart.getContext('2d')
let chart = new Chart(ctx, {
type: 'line',
data: {
datasets: [{
data
}]
},
options: {
scales: {
xAxes: [{
type: 'time',
time: {
unit: 'month',
displayFormats: {
month: 'MMM YYYY'
}
}
}],
yAxes: [{
ticks: {
callback: function(value, index, values) {
return value + 'k';
}
}
}]
}
}
})
}
})
And my Vue component named as Test.vue
<template>
<div class="To display chart">
<vx-card>
<div class="chart-container">
<LineChart></LineChart> <-- I want my chart here
</div>
</vx-card>
</div>
</template>
<script>
import LineChart from './LineChart.js'
export default {
name: 'Test'
}
</script>
I have two questions:
Nothing is displayed in my case, so I want to know how Javascript can be imported to Vue component in order to display the chart.
In my JavaScript file, I want to use API instead of data & challenge directly and the date from API should be converted just like the logic I have used, I just want to know how API can be used and the flow of it and conversion of timestamps of API s resource.
-
You have used vue api in LineChart.js. hence its vue file. should be LineChart.vue. does it have template?Nilesh Patel– Nilesh Patel2020年12月12日 12:56:15 +00:00Commented Dec 12, 2020 at 12:56
1 Answer 1
I think you are mixing some concepts, specially the "javascript file". What you are trying to do (IMO) is to attach a VueJS component (LineChart) inside another VueJS file (Test).
To do this, I recommend you to take a look at the VueJS docs about components: https://v2.vuejs.org/v2/guide/components.html
Then, you can use the "LineChart" as a normal VueJS component, (import it, use it within , etc.) and you should change the file extension from .js to .vue.
So, I recommend you to change the first file to a .vue file, and then, import it in the Test file by:
import LineChart from "@/components/LineChart.vue";
Also, the component will not render because you should attach the chart to some HTML element:
<template>
<canvas id="myChart" width="400" height="400"></canvas>
</template>
<script>
[...]
var ctx = document.getElementById('myChart').getContext('2d'); //attach to "mychart"
var myChart = new Chart(ctx, {
...
</script>
Finally, if you want to fetch data from an API, the standard way is to do with Axios: https://v2.vuejs.org/v2/cookbook/using-axios-to-consume-apis.html
And then, in the mounted cycle make the API call:
axios
.get('yourAPIURL')
.then(response => (this.data = response))
Also, as a recommendation, is better to ask 2 different questions if you have 2 problems.