我正在尝试在 vue 组件中使用 ChartJs 构建图表,但在页面上呈现它时遇到困难。有人可以告诉我我的错误在哪里吗?
// this is my HTML canvas tag
<canvas id="myChart" width="400" height="400"></canvas>
以下是我的Js代码
import Chart from 'chart.js';
export default {
methods: {
CreateChart(chartId,chartData){
const ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ['JavaScript','NodeJs','VueJs','DataBase'],
datasets: [{
label: '# of votes',
data: [12,15,23,7],
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
],
borderColor: [
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
],
borderWidth: 1
}]
},
options: {
scale: {
yAxes: [{
ticks: {beginAtZero: true}
}]
}
}
});
}
},
mounted(){
const data = {myChart}
this.CreateChart('chart',data);
}
}
提前致谢。
最佳答案
没有您应该使用scales
的scale
选项。
new Vue({
el: "#app",
methods: {
createChart(chartId,chartData){
var myChart = new Chart(this.$refs.chart.getContext("2d"), {
type: 'bar',
data: {
labels: ['JavaScript','NodeJs','VueJs','DataBase'],
datasets: [{
label: '# of votes',
data: chartData,
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
],
borderColor: [
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
],
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {beginAtZero: true}
}]
}
}
});
}
},
mounted(){
let data = [12,15,23,7]
this.createChart('chart',data);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.min.js"></script>
<div id="app">
<canvas id="chart" ref="chart" width="400" height="400"></canvas>
</div>
关于javascript - 在 Vue 组件和 Webpack cli 设置中使用 ChartJs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51477165/